我无法克服以下代码引起的“下标超出范围”错误。当我第一次设置找到的变量时,它将引发错误。
子项用于工作簿中的每个工作表,用于从已知列中搜索员工并标识该行,然后使用该行对变量求和。然后,它用该总数填充 Activity 工作表中的一个单元格。
在主子目录中指定“col”。
nDate = Range("B3")
Dim startDate As Date
startDate = Range("B2")
Dim emp As String
emp = Range("B8")
Dim rw As String
n = 0
Do While True
Range("B99") = nDate
stringDate = Range("B99").Text
Set found = Worksheets(stringDate).Range("D38:D144").Find(emp, LookIn:=xlValues, _
LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext)
If found = emp Then
rw = found.row
n = Worksheets(stringDate).Range(col + rw)
tot = tot + n
End If
If nDate = startDate Then
Exit Do
End If
nDate = nDate - 1
Loop
Range(col + "3") = tot
我的代码中有类似的Subs,可以很好地进行编译。唯一的区别是,在上面的子栏中,我正在搜索范围。
以下是不会引发错误的其他子项。
n = 0
Dim startDate As Date
Dim endDate As Date
startDate = Range("B2")
nDate = Range("B3")
Do While True
Range("B99") = nDate
stringDate = Range("B99").Text
n = Worksheets(stringDate).Range(col + rw)
tot = tot + n
If nDate = startDate Then
Exit Do
End If
nDate = nDate - 1
Loop
Range(col + "3") = tot
我知道对于相同的错误也有类似的问题,但是没有一个涉及引用外部工作表。
关于如何调试的任何建议?
最佳答案
在子/功能的开头添加以下内容:
Dim targetWs As Excel.Worksheet
然后将循环更改为:
Do While True
Range("B99") = nDate
stringDate = Range("B99").Text
Set targetWs = Nothing
Set found = Nothing
On Error Resume Next
Set targetWs = Worksheets(stringDate)
On Error GoTo 0
If targetWs Is Nothing Then
MsgBox "Worksheet not found: " & stringDate
Else
Set found = targetWs.Range("D38:D144").Find(emp, LookIn:=xlValues, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext)
End If
If Not found Is Nothing Then
If found = emp Then
rw = found.row
n = targetWs.Range(col + rw)
tot = tot + n
End If
End If
If nDate = startDate Then
Exit Do
End If
nDate = nDate - 1
Loop
如果显示一个消息框,您将知道您遇到的工作表名称不属于Worksheets集合。
关于vba - 引用另一张纸时出现“Subscript out of range”错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46944532/