简体   繁体   中英

How to open files contained in a folder in current file path

I want to open a file ( file ) that is stored in a folder ( Source ) which is in the same directory as the current workbook. I get a runtime error 1004 indicating that it the file can't be located. What am I doing worng?

Set x = Workbooks.Open(ThisWorkbook.Path & "\Source\file*.xlsx")

Since you want the wildcard to stay, you need to loop through the files in the folder. Something like this may be of interest to you:

Sub FileOpen()

Dim sPath As String
Dim sFile As String
Dim wb As Workbook

    sPath = ThisWorkbook.Path & "\Source\"
    sFile = Dir(sPath & "file*.xlsx")

    ' Loops while there is a next file found in the specified directory
    ' When there is no next file the Dir() returns an empty string ""
    Do While sFile <> ""

        ' Prints the full path of the found file
        Debug.Print sPath & sFile

        ' Opens the currently found file
        Set wb = Workbooks.Open(sPath & sFile)

        ' Place your code here
        ' Place your code here
        ' Place your code here

        ' Close the current workbook and move on to the next
        wb.Close

        ' This line calls the Dir() function again to get the next file
        sFile = Dir()

    Loop

End Sub

Good luck!

将通配符替换为实际的文件名。

Set x = Workbooks.Open(ThisWorkbook.Path & "\\Source\\file.xlsx"

I changed the file*.xlsx to file. xlsx...hope your code works.

thanks.

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