插入—模块 复制如下代码
Dim x As Integer "定义个一公有变量记录复制行数
"复制多个Excel文件中的内容到一个里
Sub combine()
x = 1
Dim folder As String
Dim count As Integer
folder = ChooseFolder()
"count = combineFiles(folder, "xls")
count = count + combineFiles(folder, "xlsx")
MsgBox (" succeed ")
End Sub
Function combineFiles(folder, appendix)
Dim MyFile As String
Dim s As String
Dim count, n, copiedlines As Integer
MyFile = Dir(folder & "\*." & appendix)
count = count + 1
n = 2
Do While MyFile <> ""
copiedlines = CopyFile(folder & "\" & MyFile, 2, n)
If copiedlines > 0 Then
n = n + copiedlines
count = count + 1
End If
MyFile = Dir
Loop
combineFiles = count
End Function
"复制数据
Function CopyFile(filename, srcStartLine, dstStartLine)
Dim book As Workbook
Dim sheet As Worksheet
Dim rc As Integer
CopyFile = 0
If filename = (ThisWorkbook.Path & "\" & ThisWorkbook.Name) Then
Exit Function
End If
Set book = Workbooks.Open(filename)
ThisWorkbook.Activate
For j = 1 To book.Sheets.count
book.Sheets(j).UsedRange.Copy Cells(x, 1)
With ActiveSheet.Cells.Find("*", Cells(1, 1), -4163, 1, 1, 2).MergeArea "通用判断最后一行
Rows(.Row + .Rows.count - 1).Select
x = Selection.Row + Selection.Rows.count - 1
End With
x = x + 1
Next j
book.Close
End Function
"选择文件夹
Function ChooseFolder() As String
Dim dlgOpen As FileDialog
Set dlgOpen = Application.FileDialog(msoFileDialogFolderPicker)
With dlgOpen
If .Show = -1 Then
ChooseFolder = .SelectedItems(1)
End If
End With
Set dlgOpen = Nothing
End Function
点击下方了解更多看视频解析