vba 循环打开文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28498367/
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
Open files with a loop
提问by user4563174
In a folder I have different Excel Workbooks like this:
在一个文件夹中,我有不同的 Excel 工作簿,如下所示:
Exercise1
Exercise2
Exercise3
...
ExerciseN
I want to open all files (all .xls) in the folder in the same Excel workbook on different sheets.
我想在不同工作表上的同一个 Excel 工作簿中打开文件夹中的所有文件(所有 .xls)。
I suppose it would be something like this, but not:
我想它会是这样的,但不是:
Sub Macro1()
For i = 1 To ??
Workbooks.Open Filename:="C:\Exercisei.xls"
Next i
End Sub
回答by Dubison
Following code is a simple sub routine to open all excel files in a defined folder. You can adjust your file names in variable. I have simplified the macro defined here Files in a Directory
以下代码是一个简单的子程序,用于打开定义文件夹中的所有 excel 文件。您可以在变量中调整文件名。我已经简化了此处定义的宏文件在目录中
Sub openfiles()
Dim directory As String, fileName As String, sheet As Worksheet, i As Integer, j As Integer
Application.ScreenUpdating = False
directory = "c:\test\"
fileName = Dir(directory & "*.xl??") '<-- you can use * and ? wild cards here.
Do While fileName <> ""
Workbooks.Open (directory & fileName)
fileName = Dir()
Loop
Application.ScreenUpdating = True
End Sub
回答by Gary's Student
This example is for 2.xls files:
此示例适用于2 个.xls 文件:
Sub qwerty()
Dim master As Workbook, awb As Workbook
Dim N As Long
Dim s1 As String, s2 As String, i As Long
N = 2
Set master = ThisWorkbook
s1 = "C:\TestFolder\Examplez.xls"
For i = 1 To N
s2 = Replace(s1, "z", CStr(i))
Workbooks.Open Filename:=s2
Set awb = ActiveWorkbook
ActiveSheet.Copy after:=master.Sheets(master.Sheets.Count)
awb.Close
Next i
End Sub
Each worksheet is copied to the master workbook and then that Example.xls is closed.
You would change the folder name and adjust the number of files to process.
每个工作表都被复制到主工作簿,然后关闭 Example.xls。
您将更改文件夹名称并调整要处理的文件数。