我有一个包含属性的工作簿,每个属性都有一个相应的属性ID。 下面的代码旨在找到与从comboBox中的列表中选择的ID相对应的行,然后使用其行中的数据填充表单中的其余字段。
Private Sub propertyCodeCombo_change()
Set wks = Application.Workbooks("Book1.xlsm").Worksheets("Property")
Dim propertyCell As Range
Set propertyCell = wks.Range("A2")
Do Until propertyCell.Value = propertyCodeCombo.Value
Set propertyCell = propertyCell.Offset(1, 0) <--Error Occurs here
Loop
addressText = propertyCell.Offset(0, 1).Value
suburbText = propertyCell.Offset(0, 2).Value
propertyTypeCombo = propertyCell.Offset(0, 3).Value
bedroomsText = propertyCell.Offset(0, 4).Value
bathroomsText = propertyCell.Offset(0, 5).Value
weeklyRentalFeeText = propertyCell.Offset(0, 6).Value
statusCombo = propertyCell.Offset(0, 7).Value
commisionText = propertyCell.Offset(0, 8).Value
ownerCodeCombo = propertyCell.Offset(0, 9).Value
End Sub
我觉得奇怪,因为我有几乎相同的代码,如下所示,不会导致错误和功能完美。
Set wks = Application.Workbooks("Book1.xlsm").Worksheets("Property")
Dim propertyCell As Range
Set propertyCell = wks.Range("A2")
Do Until IsEmpty(propertyCell)
Set propertyCell = propertyCell.Offset(1, 0)
Loop
答案 0 :(得分:1)
您的代码会收到错误,因为您找不到匹配项,因此您的“偏移”命令最终会到达工作表的最后一行。再偏移一行会导致错误。
这就是您的其他类似代码有效的原因 - 您应用了不同的测试,因此您可以提前退出循环。
使用此代码可以获得更好的性能,因为它使用的是数组而非Offset:
Private Sub propertyCodeCombo_change()
Dim wks As Worksheet
Set wks = ThisWorkbook.Worksheets("Property")
Dim propertyCell As Range
Set propertyCell = wks.Range("A2")
Dim comboValue As Variant
comboValue = propertyCodeCombo.Value
Dim props As Variant
props = wks.UsedRange.Value
If IsArray(props) Then
Dim propRow As Long
For propRow = LBound(props) To UBound(props)
If props(propRow, 1) = comboValue Then
addressText = props(propRow, 2)
suburbText = props(propRow, 3)
propertyTypeCombo = props(propRow, 4)
bedroomsText = props(propRow, 5)
bathroomsText = props(propRow, 6)
weeklyRentalFeeText = props(propRow, 7)
statusCombo = props(propRow, 8)
commisionText = props(propRow, 9)
ownerCodeCombo = props(propRow, 10)
Exit For
End If
Next propRow
End If
End Sub