我最近开始使用 VBA...我正在开发 Excel 用户窗体。我希望当用户在组合框中进行更改时自动选择列表框中的某些字段。尽管我没有做任何异常的事情,但它仍然返回“应用程序定义或对象定义的错误”。
我搜索了有关此错误的其他问题,但它们似乎都不适用于同一类型的问题。这是代码:
Private Sub ComboBox1_Change()
'first get the current row rule id
lastRow = FindLastRow("Rows Rules")
Dim id, i, k As Integer
For i = 2 To lastRow
If Sheets("Rows Rules").Cells(i, 2) = ComboBox1.Text Then
id = Sheets("Rows Rules").Cells(i, 1)
End If
Next
'get ISINs for id
With Sheets("Row ISINs")
'loop for every isin
For i = 0 To ListBox1.ListCount
isin = ListBox1.List(i, 0)
'check if exists
lastRow = FindLastRow("Row ISINs")
'loop to compare with every record
For k = 1 To lastRow
If .Cells(k, 0) = id Then 'error happens here--------------
If .Cells(k, 1) = isin Then
'mark those as selected
ListBox1.Selected(i) = True
End If
End If
Next
Next
End With
End Sub
看来在第二次循环之后:
For k = 1 To lastRow
对单元格的每次访问都会返回错误
我还尝试使用 MsgBox 检查:
MsgBox .Cells(0, 1)
它仍然返回相同的错误。
我不知道这是否与循环有关,或者是我缺少的其他内容。任何帮助将不胜感激,谢谢
最佳答案
Excel 中没有第 0 行或第 0 列。如果您想要第一行或第一列,它应该从 1 开始,如下所示:
.Cells(1,1)
关于在 2 个循环内访问单元格值时出现 VBA 错误 '1004',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31694868/