2016-06-15 58 views
1

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

我不想打开/关闭工作簿,所以我试图在随机单元格中更改公式以链接到文件路径(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 

希望你们能帮助我在这里,谢谢!

+0

有趣的看到你的例子调用这个子 - 你传递给fp的字符串是什么?如果工作簿未打开,我确信无法访问WorkSheet值 – dbmitch

+0

fp字符串包含带有[]括号的外部工作簿的路径,就像您在任何典型的链接单元格中一样。 – superzipp

回答

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 
+0

非常感谢Tim的快速回复!这确实比我的优雅和简单得多。我修改了IsError(Application.ExecuteExcel4Macro(f))行来代替错误检查器,并且它完美地工作。 – superzipp

-1

子仪()

MSGBOX(不ISERROR(Application.ExecuteExcel4Macro( “! 'C:\ TEMP [temp.xlsm] Sheetxyz' R1C1” )))

末次

+0

欢迎来到Stack Overflow!请提供一些关于您提供的代码的解释。 –

0

蒂姆的功能进行错误处理只是一个更新:

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 
相关问题