使用模式匹配VBA打开文件

时间:2018-09-10 09:23:59

标签: vba excel-vba

使用模式匹配打开文件时遇到问题。目的是打开一个具有以下样式的文件:extraction _ 20180630 _ Data - Updated.Xlsx。文件名201806的这一部分由用户通过使用变量作为文本的输入框功能设置。目的是在知道日期可以根据用户选择的目标(年和月)更改的情况下打开此文件。

这是我的代码:

Sub OpenFile 
    Dim Directory As Text
    Dim File As Text 
    Dim MainPath As Text
    Dim Y As Text
    Dim M As Text 

    Directory = "C:\Desktop\Folder\"

    Y = InputBox  ("Please Choose your target Year such as 2017")
    M = InputBox ("Please Choose your target Month such as 06 for June")

    ' File name format = "extraction _ 20180630 _ Data - Updated _V5.2.xlslx"
    File = "extraction _" &  Y  & M 
    MainPath = Directory  & File 
    Filename = Dir (MainPath & "*_ Data - Updated _*")

    On Error  Resume Next

    ' after several Checking, the MainPath is Correct. the issue is whithin the second part 
    Workbooks.Open MainPath & Filename

    If Err.Number = 1004
        MsgBox " The file was not found"
        Err.Clear
        Application.DisplayAlerts = False
        Application.Quit 
     End If
End Sub 

您可以想象,这段代码会生成一个

  

错误1004

,我检查了正确的主路径。问题在于Filename的第二部分为*_ Data - Updated _*

我该如何解决?

1 个答案:

答案 0 :(得分:1)

根据上面评论中的讨论,尝试以下操作:

' File name format = "extraction _ 20180630 _ Data - Updated _V5.2.xlsx"
File = "extraction _" & Format(DateSerial(CInt(y), CInt(M) + 1, 0), "yyyymmdd") & "_ Data - Updated*"
Filename = Dir(Directory & File)

On Error Resume Next

' after several Checking, the MainPath is Correct. the issue is whithin the second part
If Len(Filename) > 1 Then
    Workbooks.Open Directory & Filename
Else
    MsgBox "Unable to find file for pattern """ & File & """ in location " & Directory, vbCritical
End If

以下是该版本也可以回溯到3个月以查找最新文件:

' File name format = "extraction _ 20180630 _ Data - Updated _V5.2.xlsx"
Dim lRollBack As Integer
For lRollBack = 0 To 3
    File = "extraction _" & Format(DateSerial(CInt(y), CInt(M) + 1 - lRollBack, 0), "yyyymmdd") & "_ Data - Updated*"
    Filename = Dir(Directory & File)
    If Len(Filename) > 1 Then Exit For 'Stop after we find a match
Next lRollBack

On Error Resume Next

' after several Checking, the MainPath is Correct. the issue is whithin the second part
If lRollBack <= 3 Then
    If lRollBack > 0 Then
        MsgBox "We had to roll back by " & CStr(lRollBack) & " month(s)", vbInformation
    End If
    Workbooks.Open Directory & Filename
Else
    MsgBox "Unable to find file for pattern """ & File & """ in location " & Directory, vbCritical
End If