[英]“Subscript out of range” error when referencing another sheet
我无法摆脱以下代码引起的“下标超出范围”错误。 当我第一次设置找到的变量时,它将引发错误。 子项用于工作簿中的每个工作表,用于从已知列中搜索员工并标识该行,然后使用该行求和变量。 然后,它用该总数填充活动工作表中的一个单元格。 在主子目录中指定“ 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集合。
谢谢大家的帮助。 我终于能够调试潜艇了。 下面是正确运行的代码。 下标错误是在while循环的第二次迭代中出现的,这时将stringDate变量重新格式化为日期而不是字符串。 我不确定为什么它会在此子代码中发生,而在其他具有相同逻辑的代码中却没有发生。 转换为字符串的重点是在该日期格式的工作表中移动(例如,2016年10月25日)。 无论哪种方式,我都通过手动格式化保存当前迭代日期的单元格来解决。 我还改变了执行.find之后如何识别“找到”。
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
Range("B99").NumberFormat = "[$-409]mmmm d, yyyy;@"
stringDate = Range("B99").Text
Set found = Worksheets(stringDate).Range("D12:D144").Find(emp, LookIn:=xlValues, _
LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext)
If Not found Is Nothing Then
rw = found.Row
n = Worksheets(stringDate).Range(col + rw)
Else
n = 0
End If
tot = tot + n
If nDate = startDate Then
Exit Do
End If
nDate = nDate - 1
Loop
Range(col + "3") = tot
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.