简体   繁体   English

如何查找,打开和引用具有部分名称的工作簿

[英]How to find, open, and refer to workbook with partial name

I am trying to use a partial name match to locate a template file (full name On-Call Audit Sheet VXX where VXX is the version) that gets updated from the current workbook with the macro I am writing. 我正在尝试使用部分名称匹配来找到一个模板文件(全名On-Call Audit Sheet VXX ,其中VXX是版本),该文件从当前工作簿中以我正在编写的宏进行更新。

The macro needs to locate the file with a partial name match; 宏需要使用部分名称匹配来定位文件; if found then open it and define the workbook as wb1 , if not found then return an error. 如果找到,则将其打开并将工作簿定义为wb1 ,如果找不到,则返回错误。 Current code below partially inspired by this post . 下面的当前代码部分受此职位启发。

So far the macro can locate and open the file with partial name match using the FileSystemObject to grab the current folder path, but I can't work out how to then define wb1 with the partial name match. 到目前为止,宏可以使用FileSystemObject来查找和打开具有部分名称匹配的文件,以获取当前文件夹路径,但是我不知道如何然后定义具有部分名称匹配的wb1

Is there a way to get the full name of the file once the partial match is successful and thus define wb1 from that? 一旦部分匹配成功,是否有办法获取文件的全名,从而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

Your code currently works on the basis that there is only ever one file that matches your *Audit Sheet* pattern. 当前,您的代码基于以下条件工作:只有一个文件与*Audit Sheet*模式匹配。 If there are 2 or more, then it will open them all but only point wb1 at the latest. 如果有2个或更多,它将全部打开,但最晚仅指向wb1

I assume this isn't what you want. 我认为这不是您想要的。

The following will open the first that it finds (so you might want to tighten up your pattern?) : 以下内容将打开它找到的第一个(因此您可能想收紧您的模式?):

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM