【问题标题】:Checking If A Sheet Exists In An External Closed Workbook检查外部关闭的工作簿中是否存在工作表
【发布时间】: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


【解决方案1】:

这里有一个稍微不同的方法:

Sub Tester()

    Dim s As Worksheet

    For Each s In ThisWorkbook.Worksheets

        Debug.Print s.Name, HasSheet("C:\Users\blah\Desktop\", "temp.xlsm", s.Name)

    Next s


End Sub



Function HasSheet(fPath As String, fName As String, sheetName As String)

    Dim f As String

    f = "'" & fPath & "[" & fName & "]" & sheetName & "'!R1C1"

    HasSheet = Not IsError(Application.ExecuteExcel4Macro(f))

End Function

【讨论】:

  • 非常感谢蒂姆的快速回复!这确实比我所拥有的更加优雅和简单。我调整了 IsError(Application.ExecuteExcel4Macro(f)) 行来代替错误检查器,它运行良好。
【解决方案2】:

子测试器()

MsgBox (Not IsError(Application.ExecuteExcel4Macro("'C:\temp[temp.xlsm]Sheetxyz'!R1C1")))

结束子

【讨论】:

  • 欢迎来到 Stack Overflow!请围绕您提供的代码提供一些解释。
【解决方案3】:

只是对 Tim 的错误处理函数的更新:

VBA:

Function HasSheet(fPath As String, fName As String, sheetName As String)
On Error Resume Next
Dim f As String

f = "'" & fPath & "[" & fName & "]" & sheetName & "'!R1C1"

HasSheet = Not IsError(Application.ExecuteExcel4Macro(f))
If Err.Number <> 0 Then
    HasSheet = False
End If
On Error GoTo 0 
End Function

【讨论】:

    猜你喜欢
    • 2022-07-11
    • 2012-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-15
    • 1970-01-01
    • 2018-09-08
    相关资源
    最近更新 更多