Vba Visual Basic,检查其他工作簿中是否存在工作表
我对VisualBasic非常陌生,我也不懂任何python,我正在尝试编写能够检查工作簿中是否存在工作表的代码Vba Visual Basic,检查其他工作簿中是否存在工作表,vba,excel,file-io,Vba,Excel,File Io,我对VisualBasic非常陌生,我也不懂任何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
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日的工作表,但代码仅返回“工作表不存在”,是否有其他方法检查其他工作簿中的工作表?我认为您误用了
Dir
功能
检查工作表是否存在的最简单方法是错误处理
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
:
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
我认为您在此处错误地使用了
Dir
功能。该功能可用于检查文件或文件夹路径的有效性。工作簿“ABCD-Performanx.xls”是否已打开,或者您是否正在尝试查找该工作表是否存在于已关闭的工作簿中?您需要打开工作簿以检查该工作簿中是否存在工作表。Dir()
无法处理您正在尝试的内容。请参阅:是否有方法检查关闭的工作簿中是否存在工作表?这就是我试图完成的任务…是的,请参阅下面更新的答案中的代码。可以使用ExecuteExcel4Macro
方法查询关闭的工作簿。谢谢,我将测试它!
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