1
votes

I am using excel 2010. I am trying to find the first worksheet with an empty "A1" cell. This workbook is very big and everything works with no errors until iteration 203, where I get "Error 9: Subscript out of range". I do not understand why this happens. My code should find the first empty "A1" cell on worksheet 220, so it is odd that I get the error on worksheet 203. Cell "A1" in worksheet 203 is not different than the "A1" cells of the worksheets preceding it. A portion of my code is attached below.

Public Sub CommandButton1_Click()

Dim firstCell As String  
    Dim i As Integer  
    i = 1
    firstCell = ThisWorkbook.Sheets(i).Cells(1, 1)  
    Do Until firstCell = "" Or i = 300  
        i = i + 1  
        firstCell = ThisWorkbook.Sheets(i).Cells(1, 1)  
    Loop
end sub
2

2 Answers

0
votes

Rather than iterating through your worksheets with the worksheet number, use the Worksheet object and let VBA do all the hard work for you

Public Sub CommandButton1_Click()
    Dim ws As Worksheet

    For Each ws In ThisWorkbook.Worksheets
        If ws.Index > 5 and ws.Range("A1").Value = vbNullString Then
            'do something
            Exit For
        End If
    Next ws
End Sub
0
votes

Sub forEachWSinWB() Dim ws As Worksheet Dim wb As Workbook Dim wsCounter As Long

For Each ws In ThisWorkbook.Worksheets  'amend as appropriate
    wsCounter = wsCounter + 1
    If wsCounter > 6 Then
        Debug.Print ws.Name ' do what you need to here
    End If

Next ws

End Sub

or go to https://support.microsoft.com/en-us/help/142126/macro-to-loop-through-all-worksheets-in-a-workbook