VBA运行时错误9

我目前收到一个错误,说下标超出范围。 在代码行上

If Sheets(Master).Cells(i, A).Value = AssetNum.Value Then 

我试图使用for循环来增加我,所以行范围从12开始,每增加1。 然后在for循环中,我想使用If语句来检查单元格(i,A)是否等于AssetNum中的值。 如果循环达到EmptyRow的值,则结束循环。 我不是很确定如何正确使用for循环IF-THen语句。

 Public i As Integer Private Sub AssetNum_Change() End Sub Private Sub Enter_Click() Dim EmptyRow As Long 'Audit will only search Master Sheet Worksheets("Master").Activate 'Find empty row value so we can use that for limit of search With Sheets("Master") EmptyRow = .Range("A" & Rows.Count).End(xlUp).Row + 1 End With 'i needs to be set to minimum limit 'Begin loop of search For i = 12 To EmptyRow + 1 If Cells(i, 1).Value = AssetNum.Value Then 'Go to compare userform to display Compare.AssetDisplay.Value = AssetNum.Value Compare.LocationDisply.Value = Cells(i, 2).Value Compare.Show End If Next i 'If i gets to emptyrow num then go to non found asset userform Unload Me NonFoundAsset.Show 

我假设你的错误提交到该行:

 If Cells(i, A).Value = AssetNum.Value Then 

那么,我没有看到A被宣布。 然后VBA自动声明它(build议: 总是把Tools,Options,要求variables声明为ON )。 我也没有看到A被初始化,所以它的值将是0 ,这不是一个Cells的有效参考。 因此,下标越界。

如果你想引用“A”列,然后写:

 If Cells(i, 1).Value = AssetNum.Value Then 

因为“A”是第一列。

使用如下:

 If Sheets(Master).Cells(i, "A").Value = AssetNum.Value Then 

还有这一行:

 Compare.LocationDisply.Value = Cells(i, "B").Value