Thursday, July 14, 2011

VBA excel - sheets exist ?

The function:
Public Function SheetExists(SheetName As String) As Boolean
    Dim ws As Worksheet
    SheetExists = False
    For Each ws In ThisWorkbook.Worksheets
        If ws.Name = SheetName Then SheetExists = True
    Next ws
End Function
create sheet if it does not exist:
For i = 1 to n
    If SheetExists("Sheet" & CStr(i)) Then
        MsgBox ("Sheet" & CStr(i) & " exists")
    Else
        Worksheets.Add(After:=Worksheets(Worksheets.Count)).Name = "Sheet" & CStr(i)
    End If
Next i

No comments :

Post a Comment