I’m trying to create sheets if two specific strings are found in columns G
and K
in the same row.
No sheet is created after running the following code:
Sub CreateSheets()
Dim newSheet As Worksheet
Dim lastRow As Long
Dim i As Long
Dim sheetExists As Boolean
Dim ws As Worksheet
' Find the last row with data in column A
lastRow = Cells(Rows.Count, "A").End(xlUp).Row
' Check for the B2B GBP condition
sheetExists = False
For Each ws In ThisWorkbook.Sheets
If ws.Name = "B2B GBP" Then
sheetExists = True
Exit For
End If
Next ws
If Not sheetExists Then
For i = 1 To lastRow
If Cells(i, "K").Value = "GBP" And Cells(i, "G").Value = "OK - B2B" Then
Set newSheet = ThisWorkbook.Sheets.Add(After:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count))
newSheet.Name = "B2B GBP"
Exit For
End If
Next i
End If
' Check for the IMPORT GBP condition
sheetExists = False
For Each ws In ThisWorkbook.Sheets
If ws.Name = "IMPORT GBP" Then
sheetExists = True
Exit For
End If
Next ws
If Not sheetExists Then
For i = 1 To lastRow
If Cells(i, "K").Value = "GBP" And Cells(i, "G").Value = "OK - IMPORTACAO" Then
Set newSheet = ThisWorkbook.Sheets.Add(After:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count))
newSheet.Name = "IMPORT GBP"
Exit For
End If
Next i
End If
End Sub
What’s wrong with the code?
New contributor
Martino Lamaison de Souza is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.