简体   繁体   English

VBA-尝试打开文件夹中的所有工作簿

[英]VBA - Trying to open all workbooks in a folder

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. 我试图遍历并打开名为(BU)的文件夹中的所有文件,该文件夹与宏所在的工作表位于同一目录中。 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. 我能够看到myfile正确获取了第一个文件名,但是当工作簿尝试打开时,我遇到了运行时错误1004。 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. 编辑:我最终使用了Unicco的程序,它运行良好。

You can use this procedure instead. 您可以改用此过程。

Modify "ThisWorkbook.Path" and ".xlsm" to your desired purpose. 修改“ ThisWorkbook.Path”和“ .xlsm”以达到所需的目的。 Use InStr(objFile, ".xlsm") Or InStr(objFile, ".xlsx") if you want to open both standard aswell as Excelfiles with macros. 如果要同时打开标准和带有宏的Excelfile,请使用InStr(objFile,“ .xlsm”)或InStr(objFile,“ .xlsx”)。

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

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. Dir()仅返回文件名,而不返回完整路径:除非当前目录碰巧是您要搜索的目录,否则您需要将完整路径传递给Open() It's best never to rely on that being the case. 最好永远不要依赖这种情况。

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

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