宏 - 打开文件夹中的所有文件

19

我想打开指定文件夹中的所有文件,以下是我的代码:

Sub OpenFiles()
Dim MyFolder As String
Dim MyFile As String
MyFolder = "\\ILAFILESERVER\Public\Documents\Renewable Energy\FiTs\1 Planning
           Department\Marks Tracker\Quality Control Reports"
MyFile = Dir(MyFolder & "\*.xlsx")
Do While MyFile <> ""
Workbooks.Open Filename:=MyFolder & "\" & MyFile
Loop
End Sub

我的问题是它一直尝试重复打开文件夹中的第一个文件,但不会继续进行。有人能帮忙吗?我对VBA有点生疏,真的需要一些帮助。我正在尝试打开大约30份报告,它们都是以 .xlsx 格式存在的。非常感谢提前。


你想同时打开一个文件夹中的所有文件吗? - Anderson Green
3个回答

33

loop 之前加入这一行代码。

    MyFile = Dir
Loop

6
你好,Ross,欢迎来到StackOverflow!在这里,惯例是通过点击答案旁边的“接受答案”按钮来感谢他人,该按钮的形状像一个大勾号。这样做可以让帮助你的人获得积分作为奖励,同时也为你贡献有益的问答页面获取信用。 - Harald Brinkhof

3
你可以在循环检查语句中使用 Len(StrFile) > 0
Sub openMyfile()

    Dim Source As String
    Dim StrFile As String

    'do not forget last backslash in source directory.
    Source = "E:\Planning\03\"
    StrFile = Dir(Source)

    Do While Len(StrFile) > 0                        
        Workbooks.Open Filename:=Source & StrFile
        StrFile = Dir()
    Loop
End Sub

1
尝试以下代码:

Sub opendfiles()

Dim myfile As Variant
Dim counter As Integer
Dim path As String

myfolder = "D:\temp\"
ChDir myfolder
myfile = Application.GetOpenFilename(, , , , True)
counter = 1
If IsNumeric(myfile) = True Then
    MsgBox "No files selected"
End If
While counter <= UBound(myfile)
    path = myfile(counter)
    Workbooks.Open path
    counter = counter + 1
Wend

End Sub

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接