如何查找、打开和引用具有部分名称的工作簿
How to find, open, and refer to workbook with partial name
我正在尝试使用部分名称匹配来定位模板文件(全名 On-Call Audit Sheet VXX
,其中 VXX 是版本),该文件是使用我正在编写的宏从当前工作簿更新的。
宏需要找到部分名称匹配的文件;如果找到则打开它并将工作簿定义为 wb1
,如果未找到则 return 错误。下面的当前代码部分受 .
启发
到目前为止,宏可以使用 FileSystemObject
找到并打开部分名称匹配的文件以获取当前文件夹路径,但我不知道如何定义 wb1
部分名称匹配。
有没有办法在部分匹配成功后获取文件的全名,从而从中定义 wb1
?
Sub anotherTest()
Dim fso As FileSystemObject
Dim fldBase As Folder
Dim wb1 As Workbook
Dim ws1 As Worksheet
Set fso = New FileSystemObject
'determining current folder location based on where the dashboard file is
Set fldBase = fso.GetFolder(ThisWorkbook.Path)
For Each Item In fldBase.Files
If InStr(Item.Name, "*Audit Sheet*") Then
Workbooks.Open (fldBase & "\" & Item.Name) '<-- Open workbook
Set wb1 = Workbooks(fldBase & "\" & Item.Name) '<-- set workbook to wb1, THIS BIT DOESNT WORK
Else
MsgBox "File not found" '<-- if not found exit sub after showing error
Exit Sub
End If
Next
'Rest of the macro
End Sub
您的代码目前的工作原理是只有一个文件与您的 *Audit Sheet*
模式相匹配。如果有2个或更多,那么它将全部打开,但最迟只打开wb1
。
我想这不是你想要的。
以下将打开它找到的第一个(所以您可能想收紧您的模式?):
Sub Test()
Dim fldBase As String
Dim filefound As String
Dim wb1 As Workbook
Dim ws1 As Worksheet
fldBase = "C:\yourbasefolder"
filefound = Dir(fldBase & "\" & "*Audit Sheet*.xlsm")
If filefound = "" Then
MsgBox "File not found" '<-- if not found exit sub after showing error
Exit Sub
Else
Set wb1 = Workbooks.Open(fldBase & "\" & filefound)
End If
'Rest of the macro
End Sub
我正在尝试使用部分名称匹配来定位模板文件(全名 On-Call Audit Sheet VXX
,其中 VXX 是版本),该文件是使用我正在编写的宏从当前工作簿更新的。
宏需要找到部分名称匹配的文件;如果找到则打开它并将工作簿定义为 wb1
,如果未找到则 return 错误。下面的当前代码部分受
到目前为止,宏可以使用 FileSystemObject
找到并打开部分名称匹配的文件以获取当前文件夹路径,但我不知道如何定义 wb1
部分名称匹配。
有没有办法在部分匹配成功后获取文件的全名,从而从中定义 wb1
?
Sub anotherTest()
Dim fso As FileSystemObject
Dim fldBase As Folder
Dim wb1 As Workbook
Dim ws1 As Worksheet
Set fso = New FileSystemObject
'determining current folder location based on where the dashboard file is
Set fldBase = fso.GetFolder(ThisWorkbook.Path)
For Each Item In fldBase.Files
If InStr(Item.Name, "*Audit Sheet*") Then
Workbooks.Open (fldBase & "\" & Item.Name) '<-- Open workbook
Set wb1 = Workbooks(fldBase & "\" & Item.Name) '<-- set workbook to wb1, THIS BIT DOESNT WORK
Else
MsgBox "File not found" '<-- if not found exit sub after showing error
Exit Sub
End If
Next
'Rest of the macro
End Sub
您的代码目前的工作原理是只有一个文件与您的 *Audit Sheet*
模式相匹配。如果有2个或更多,那么它将全部打开,但最迟只打开wb1
。
我想这不是你想要的。
以下将打开它找到的第一个(所以您可能想收紧您的模式?):
Sub Test()
Dim fldBase As String
Dim filefound As String
Dim wb1 As Workbook
Dim ws1 As Worksheet
fldBase = "C:\yourbasefolder"
filefound = Dir(fldBase & "\" & "*Audit Sheet*.xlsm")
If filefound = "" Then
MsgBox "File not found" '<-- if not found exit sub after showing error
Exit Sub
Else
Set wb1 = Workbooks.Open(fldBase & "\" & filefound)
End If
'Rest of the macro
End Sub