在这个解决方案,我用的FileDialog用于选择多个文件。 之后,你需要循环所有thoes文件一个循环。 在For循环中,您必须打开文件并导入工作表。在本例中,我导入了工作簿所有的表格。 代码完成导入后关闭源工作簿并对其余文件执行相同操作。
Sub Import Files()
Dim sheet As Worksheet
Dim total As Integer
Dim intChoice As Integer
Dim strPath As String
Dim i As Integer
Dim wbNew As Workbook
Dim wbSource As Workbook
Set wbNew = Workbooks.Add
'allow the user to select multiple files
Application.FileDialog(msoFileDialogOpen).AllowMultiSelect = True
'make the file dialog visible to the user
intChoice = Application.FileDialog(msoFileDialogOpen).Show
Application.ScreenUpdating = False
Application.DisplayAlerts = False
'determine what choice the user made
If intChoice <> 0 Then
'get the file path selected by the user
For i = 1 To Application.FileDialog(msoFileDialogOpen).SelectedItems.Count
strPath = Application.FileDialog(msoFileDialogOpen).SelectedItems(i)
Set wbSource = Workbooks.Open(strPath)
For Each sheet In wbSource.Worksheets
total = wbNew.Worksheets.Count
wbSource.Worksheets(sheet.Name).Copy _
after:=wbNew.Worksheets(total)
Next sheet
wbSource.Close
Next i
End If
End Sub
如果你想获得所有文件,您可以更改ApplicationFile对话与循环目录是你循环目录是这样的:
directory = "c:\test\"
fileName = Dir(directory & "*.xl??")
Do While fileName <> ""
'Put Code From For Loop here.
Loop
什么类型的文件有那些? – Moosli
你可以遍历一个文件夹中的所有Excel文件并做你想做的事,这会工作吗? – Lowpar
这些文件是dat文件,是的,我想能够以某种方式循环 –