功能:遍歷用戶指定的文件夾,把文件夾中所有的excel文件的第一個表格的數據復制到本excel文件中。注意,每個excel文件中有效數據行的判斷標准是A列的最后一個有數據的單元格的行號,比如A列到第10行結束,B列到第11行結束,那么程序將不會復制第11行。
說明:鄙人也不是大閑人,也就沒有去迎合各種需求,只是根據自己的需要去寫的,拿出來分享一下。
閑話少說,直接上代碼,復制到宏命令代碼里面,執行combine宏即可實現。
Sub combine() Dim folder As String Dim count As Integer folder = ChooseFolder() count = combineFiles(folder, "xls") 'count = count + combineFiles(folder, "xlsx") 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) Set sheet = book.Sheets(1) '使用第一個sheet rc = sheet.Range("A65536").End(xlUp).Row If rc >= srcStartLine Then sheet.Rows(srcStartLine & ":" & rc).copy ThisWorkbook.Sheets(1).Range("A" & dstStartLine) '復制到指定位置 CopyFile = rc - srcStartLine + 1 End If 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