VBA - Trying to open all workbooks in a folder

2019-08-14 06:57发布

I'm trying to loop through and open all files in a folder named (BU) located in the same directory as the sheet where my macro is. I am able to see the myfile get the first file name correctly, but I am getting a run time error 1004 when the workbook tries to open. Any help would be appreciated.

Sub LoopAndOpen()

  Dim myfile As String, Sep As String, stringA As String, path1 As String
  Sep = Application.PathSeparator
  path1 = ActiveWorkbook.Path & Sep & "BU" & Sep

  myfile = Dir(path1 & "*.xlsm")

  Do While myfile <> ""

     Workbooks.Open myfile
     myfile = Dir()
  Loop

End Sub

Edit: I ended up using Unicco's procedure and it worked perfectly.

2条回答
一夜七次
2楼-- · 2019-08-14 07:35

Dir() only returns the file name, not the full path: you need to pass the full path to Open() unless the current directory happens to be the one you're searching through. It's best never to rely on that being the case.

查看更多
乱世女痞
3楼-- · 2019-08-14 07:49

You can use this procedure instead.

Modify "ThisWorkbook.Path" and ".xlsm" to your desired purpose. Use InStr(objFile, ".xlsm") Or InStr(objFile, ".xlsx") if you want to open both standard aswell as Excelfiles with macros.

Option Explicit
Sub OpenAllFiles()

    Dim objFSO As Object
    Dim objFolder As Object
    Dim objFile As Object

    Set objFSO = CreateObject("Scripting.FileSystemObject")

    Set objFolder = objFSO.GetFolder(ThisWorkbook.Path)

    For Each objFile In objFolder.Files
        If InStr(objFile, ".xlsm") Then
            Workbooks.Open (objFile)
        End If
    Next

End Sub
查看更多
登录 后发表回答