2012-06-22 42 views
9

我想在一个指定的文件夹中打开的所有文件,并有下面的代码在打开的所有文件宏观 - 文件夹

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

+0

是否要同时打开文件夹中的所有文件? –

回答

20

你之前loop

MyFile = Dir 
Loop 
+0

你好Siddharth,完美的作品。非常感谢 –

+4

嗨,罗斯,欢迎来到StackOverflow!在这里,习惯上通过点击答案旁边的“接受为答案”按钮来感谢他人。它形状像一个大复选标记。通过这种方式,您的帮手可以获得积分,作为帮助您的奖励,并因为您提供有用的问答网页而获得荣誉。 –

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 
0

可以在回路检查语句中使用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