在一个文件夹中,我有不同的Excel工作簿,如下所示:
Exercise1
Exercise2
Exercise3
...
ExerciseN
我想打开不同工作表上同一Excel工作簿中文件夹中的所有文件(全部.xls)。
我想它会是这样的,但不是:
Sub Macro1()
For i = 1 To ??
Workbooks.Open Filename:="C:\Exercisei.xls"
Next i
End Sub
答案 0 :(得分:2)
此示例适用于 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
将每个工作表复制到主工作簿,然后关闭Example.xls。
您将更改文件夹名称并调整要处理的文件数。
答案 1 :(得分:1)
以下代码是一个简单的子例程,用于打开已定义文件夹中的所有Excel文件。您可以在变量中调整文件名。我简化了这里定义的宏Files in a Directory
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