【发布时间】:2016-10-15 21:38:11
【问题描述】:
我想测试当前工作簿中的某些工作表是否存在于另一个已关闭的工作簿中,并返回一条消息,说明哪些工作表导致错误。
我不喜欢打开/关闭工作簿,因此我尝试更改随机单元格中的公式以链接到文件路径 (fp) 的工作簿以测试工作表是否存在。
我已经使用我知道在另一个工作簿中不存在的虚拟工作表对此进行了测试,并且它可以工作,但是当我有多个导致错误的工作表时,我会收到“应用程序定义的或对象定义的错误” .在第二次迭代中,我相信错误处理的编写方式会导致崩溃,但我并不完全理解它是如何工作的。
我得到的代码是:
Sub SheetTest(ByVal fp As String)
Dim i, errcount As Integer
Dim errshts As String
For i = 2 To Sheets.Count
On Error GoTo NoSheet
Sheets(1).Range("A50").Formula = "='" & fp & Sheets(i).Name & "'!A1"
GoTo NoError
NoSheet:
errshts = errshts & "'" & Sheets(i).Name & "', "
errcount = errcount + 1
NoError:
Next i
Sheets(1).Range("A50").ClearContents
If Not errshts = "" Then
If errcount = 1 Then
MsgBox "Sheet " & Left(errshts, Len(errshts) - 2) & " does not exist in the Output file. Please check the sheet name or select another Output file."
Else
MsgBox "Sheets " & Left(errshts, Len(errshts) - 2) & " do not exist in the Output file. Please check each sheet's name or select another Output file."
End If
End
End If
End Sub
希望大家能帮帮我,谢谢!
【问题讨论】:
-
有趣的是看到一个你称之为 sub 的例子 - 你将什么传递给 fp 字符串?如果工作簿未打开,我相当确定您无法访问 WorkSheet 值
-
fp 字符串包含带有 [ ] 括号的外部工作簿的路径,就像在任何典型的链接单元格中一样。
标签: vba excel error-handling