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 格式的报告。提前谢谢了。

4

3 回答 3

30

您必须在之前添加此行loop

    MyFile = Dir
Loop
于 2012-06-22T08:58:35.040 回答
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
于 2015-05-19T04:25:32.413 回答
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
于 2013-02-15T09:37:14.550 回答