Visual Basic,检查另一个工作簿中是否存在工作表

我真的是新来的Visual Basic,我也不知道任何Python,我试图编写的代码,可以检查工作簿中是否存在一个工作表…

Sub sheetexist() If Len(Dir(("C:\My Data\Performance Spreadsheets\[ABCD - Performance.xls]Jun 14"))) Then MsgBox "Sheet exist" Else MsgBox "Sheet does not exist" End If End Sub 

ABCD确实有6月14日的工作表,但代码只返回“工作表不存在”,还有其他方法来检查其他工作簿中的工作表?

我想你错了使用Dirfunction。

检查表单是否存在的最简单方法是使用error handling。

 Function SheetExists(wbPath as String, shName as String) Dim wb as Workbook Dim val 'Assumes the workbook is NOT open Set wb = Workbooks.Open(wbPath) On Error Resume Next val = wb.Worksheets(shName).Range("A1").Value SheetExists = (Err = 0) 'Close the workbook wb.Close End Function 

从工作表单元格调用这样的函数:

 =SheetExists("C:\My Data\Performance Spreadsheets\ABCD - Performance.xls", "Jun 14") 

或者从VBA如:

 Debug.Print SheetExists("C:\My Data\Performance Spreadsheets\ABCD - Performance.xls", "Jun 14") 

没有打开工作簿,你可以在这里使用代码。

如果公式的任何部分无法评估(例如,如果您传递不存在的工作表的名称, Error 2023文件path等,则会引发错误, Error 2023

 Private Function GetInfoFromClosedFile(ByVal wbPath As String, _ wbName As String, wsName As String, cellRef As String) As Variant Dim arg As String GetInfoFromClosedFile = "" If Right(wbPath, 1) <> "\" Then wbPath = wbPath & "\" If Dir(wbPath & "\" & wbName) = "" Then Exit Function arg = "'" & wbPath & "[" & wbName & "]" & _ wsName & "'!" & Range(cellRef).Address(True, True, xlR1C1) On Error Resume Next GetInfoFromClosedFile = ExecuteExcel4Macro(arg) End Function 

叫它:

 Sub Test() Dim path As String Dim filename As String Dim sheetName As String Dim cellAddress As String path = "c:\users\you\desktop" filename = "file.xlsx" sheetName = "Jun 14" cellAddress = "A1" Dim v As Variant 'MUST BE VARIANT SO IT CAN CONTAIN AN ERROR VALUE v = GetInfoFromClosedFile(path, filename, sheetName, cellAddress) If IsError(v) Then MsgBox "Sheet or filename doesn't exist!" End Sub