I'm using the following code to check in a workbook whether sheet1
and sheet2
exist or not. If they do not exist then they're supposed to be generated. Otherwise, nothing should happen.
My problem is the macro only works for the first iteration when neither of the worksheets exists. Once the worksheets are created I get an error. Something like "Name already exists. Choose a different one…." I don't want anything to happen if sheet1
and sheet2
already exist.
Sub Worksheet()
Dim x As Integer, blnFound1 As Boolean, blnFound2 As Boolean
blnFound1 = False
blnFound2 = False
With ThisWorkbook
For x = 1 To .Sheets.Count
If .Sheets(x).Name = "Sheet1" Then
blnFound1 = True
Exit For
End If
If .Sheets(x).Name = "Sheet2" Then
blnFound2 = True
Exit For
End If
Next x
If blnFound1 = False Then
.Sheets.Add
With ActiveSheet
.Name = "Sheet1"
End With
End If
If blnFound2 = False Then
.Sheets.Add
With ActiveSheet
.Name = "Sheet2"
End With
End If
End With
End Sub