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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11152870/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 13:22:29  来源:igfitidea点击:

macro - open all files in a folder

excel-vbaexcel-2010vbaexcel

提问by Ross McLaughlin

I want to open all files in a specified folder and have the following code

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

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

The problem I have is that it just keeps trying to open the first file in the folder repeatedly and won't move on. Can anybody help, I'm a bit of a novice at VBA and could really do with some assistance. I'm trying to open around 30 reports that are all in .xlsx format. Many thanks in advance.

我遇到的问题是它只是不断尝试重复打开文件夹中的第一个文件,而不会继续。任何人都可以提供帮助,我是 VBA 的新手,确实可以提供一些帮助。我正在尝试打开大约 30 个都是 .xlsx 格式的报告。提前谢谢了。

回答by Siddharth Rout

You have to add this line just before loop

您必须在此之前添加此行 loop

    MyFile = Dir
Loop

回答by josef

You can use Len(StrFile) > 0in loop check statement !

您可以Len(StrFile) > 0在循环检查语句中使用!

Sub openMyfile()

    Dim Source As String
    Dim StrFile As String

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

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

回答by Satish

Try the below code:

试试下面的代码:

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