插入—模塊 復制如下代碼
Dim x As Integer '定義個(gè)一公有變量記錄復制行數
'復制多個(gè)Excel文件中的內容到一個(gè)里
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
點(diǎn)擊下方了解更多看視頻解析
聯(lián)系客服