我遇到了一个奇怪的 VBA 错误 91 问题。我看到很多其他人都有这个问题,因为他们没有使用关键字“Set”作为对象,而我的情况不是这样。
以下是我的代码:
Dim eventWS As Worksheet
Set eventWS = Worksheets("Event Sheet")
Dim eventRange As Range
Set eventRange = eventWS.Columns("A:A").Find(240, , xlValues, xlWhole)
If Not eventRange Is Nothing Then
Dim eventFirstAddress As String
eventFirstAddress = eventRange.Address
Do
If eventWS.Range("L" & eventRange.Row).Value = busId Then
If commuter = True Then
Count = Count + Affected(eventWS.Range("Q" & eventRange.Row).Value)
Else
Count = Count + 1
End If
End If
MsgBox("Before call move next: " & eventRange.Row )
Set eventRange = eventWS.Columns("A:A").FindNext(eventRange)
MsgBox("After call move next: " & eventRange.Row )
Loop While Not eventRange Is Nothing And eventRange.Address <> eventFirstAddress
End If
Affected() 是一个我可以调用来进行内部处理的函数。如果我删除了这个“Count = Count + Affected(....)”,代码工作正常。如果我添加它,“Loop While”会抛出错误 91。如果我添加一个消息框来打印移动 eventRange 前后的行号,结果是“MsgBox(”After call move next:” & eventRange.Row )" 会抛出错误 91。
因此,我现在很困惑这个问题是由内部函数还是由 eventRange 引起的。希望有人能指出我的错误。非常感谢。
以下是内部函数的代码:
Function Affected(markerId As Integer) As Integer
'initialized return value'
AffectedCoummters = 0
'get total financial sheets'
Dim totalFinancial As Integer
totalFinancial = 0
For Each ws In Worksheets
If InStr(ws.Name, "Financial") > 0 Then
totalFinancial = totalFinancial + 1
End If
Next
Dim i As Integer
'run through all financial sheets'
For i = 1 To totalFinancial
'get current financial sheet'
Dim financialWS As Worksheet
Set financialWS = Worksheets("Financial Sheet" & i)
'get total rows of current operation sheet'
Dim rowSize As Long
rowSize = financialWS.Range("A" & financialWS.Rows.Count).End(xlUp).Row
'if reach the maximum number of rows, the value will be 1'
'reInitialize rowSize based on version of Excel'
If rowSize = 1 Then
If Application.Version = "12.0" Then
'MsgBox ("You are using Excel 2007")'
If InStr(ThisWorkbook.Name, ".xlsx") > 0 Then
rowSize = 1048576
Else
'compatible mode'
rowSize = 65536
End If
ElseIf Application.Version = "11.0" Then
'MsgBox ("You are using Excel 2003")'
rowSize = 65536
End If
End If
'filter by marker id first inside current financial sheet'
Dim findMarker As Range
Set findMarker = financialWS.Columns("K:K").Find(markerId, , xlValues, xlWhole)
'if found any given marker id'
If Not findMarker Is Nothing Then
Dim firstAddress As String
firstAddress = findMarker.Address
'check all matched marker id'
Do
AffectedCommuters = AffectedCommuters + financialWS.Range("O" & findMarker.Row).Value
'move to next'
Set findMarker = financialWS.Columns("K:K").FindNext(findMarker)
Loop While Not findMarker Is Nothing And findMarker.Address <> firstAddress
End If
Next i
End Function