我正在尝试使用部分名称匹配来找到一个模板文件(全名On-Call Audit Sheet VXX
,其中VXX是版本),该文件从当前工作簿中以我正在编写的宏进行更新。
宏需要找到名称部分匹配的文件;如果找到,则将其打开并将工作簿定义为wb1
,如果找不到,则返回错误。下面的当前代码部分受this post的启发。
到目前为止,宏可以使用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
答案 0 :(得分:2)
您的代码当前的工作原理是,只有一个文件与您的*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