VBA:在多次迭代之后,下标超出范围

我正在使用excel 2010.我试图find一个空的“A1”单元格的第一个工作表。 这个工作簿是非常大的,一切工作没有错误,直到迭代203,我得到“错误9:下标超出范围”。 我不明白为什么会发生这种情况。 我的代码应该在工作表220上find第一个空的“A1”单元,所以我在工作表203上得到这个错误是很奇怪的。工作表203中的单元“A1”与它前面工作表的单元“A1”没有什么不同。 我的代码的一部分附在下面。

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 

而不是迭代工作表编号的工作表,使用Worksheet对象,让VBA为您做所有的辛苦工作

 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 

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 

或者访问https://support.microsoft.com/zh-CN/help/142126/macro-to-loop-through-all-worksheets-in-a-workbook