简体   繁体   中英

Opening an excel file using a wildcard in VBA

This one is giving me quite a headache as none of the solutions I found online work for me.

I have a folder with a number of excel files which are always named with an alpha-2 country code and a random date (eg GB-YYYY-MD.xlsx). I need to pass the path and the country code as variables to function which opens the file. The dates in filename are not relevant to this and are kind of random, thus I need to replace them with a wildcard. With the example earlier I imagine something like 'path & "\" & countrycode & *.xlsx'. I have learned that this will not work directly with 'Workbooks.open' as it would pass the asterix into the filename instead of it being a wildcard.

Essentially, I need to open a file based on the path and country code provided by variables, perform some actions in it, save and close. Then I need to do the same for the next file and so on. This part I have figured out, however I am unable to get the workbooks open.

A lot of the solutions online discuss the Dir() function in combination with a loop however I don't seem to be able to get it to work as it always returns an empty string. I'm unclear on how to approach this and as you can see I am no VBA expert :D. Any help would be much appreciated.

Check this code, running the sub 'fnTest'. As a matter of exercise I put the parameters to return a valid file name. If there is only one file that correspond to, say, "GB*.*, this code will return it correctly.

Option Explicit

Sub fnTest()
    Dim strFileToOpen As String

    strFileToOpen = fnDirSomeFile("C:\Windows\System32\", "GP")
    If strFileToOpen <> "" Then
        MsgBox strFileToOpen
        'here is what goes on
        'Workbooks.Open strFileToOpen
    End If
    
End Sub

Function fnDirSomeFile(ByVal strPath As String, ByVal strCountry As String) As String
    Dim strFile As String
    Dim strCheckFile As String

    If Right(strPath, 1) <> "\" Then
        strPath = strPath & "\"
    End If
    
    strFile = Dir(strPath & strCountry & "*.*", vbNormal)
    fnDirSomeFile = strFile
    
lblExit:
    
End Function

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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