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\1 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格式的报告。提前谢谢了。
3 个解决方案
#1
21
You have to add this line just before loop
你必须在循环之前添加这一行
MyFile = Dir
Loop
#2
1
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
#3
0
You can use Len(StrFile) > 0
in 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\03\"
StrFile = Dir(Source)
Do While Len(StrFile) > 0
Workbooks.Open Filename:=Source & StrFile
StrFile = Dir()
Loop
End Sub
#1
21
You have to add this line just before loop
你必须在循环之前添加这一行
MyFile = Dir
Loop
#2
1
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
#3
0
You can use Len(StrFile) > 0
in 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\03\"
StrFile = Dir(Source)
Do While Len(StrFile) > 0
Workbooks.Open Filename:=Source & StrFile
StrFile = Dir()
Loop
End Sub