检查外部关闭工作簿中是否存在工作表



我想测试当前工作簿中的某些工作表是否存在于另一个关闭的工作簿中,并返回一条消息,说明哪个工作表导致错误。

我不想打开/关闭工作簿,所以我尝试更改随机单元格中的公式以链接到文件路径 (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 Tester()
    Dim s As Worksheet
    For Each s In ThisWorkbook.Worksheets
        Debug.Print s.Name, HasSheet("C:UsersblahDesktop", "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

只是 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

Sub Tester()

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

结束子

最新更新