请生成一段VBA代码把当前文件夹中目录的所有工作簿汇总到一个工作簿
Sub CombineWorkbooks()
Dim myPath As String
Dim myFile As String
Dim myExtension As String
Dim myWorkbook As Workbook
Dim targetWorkbook As Workbook
' Set the path to the folder containing the workbooks to be combined
myPath = "C:\Users\User\Documents\TestFolder\"
' Set the file extension of the workbooks to be combined
myExtension = "*.xlsx"
' Create a new workbook to store the combined data
Set targetWorkbook = Workbooks.Add
' Loop through all files in the folder with the specified extension
myFile = Dir(myPath & myExtension)
Do While myFile <> ""
' Open each workbook in turn
Set myWorkbook = Workbooks.Open(myPath & myFile)
' Copy the data from each worksheet in the workbook to the target workbook
For Each ws In myWorkbook.Worksheets
ws.Copy After:=targetWorkbook.Sheets(targetWorkbook.Sheets.Count)
Next ws
' Close the workbook without saving changes
myWorkbook.Close SaveChanges:=False
' Get the next file name
myFile = Dir
Loop
' Save the target workbook with a new name
targetWorkbook.SaveAs Filename:=myPath & "CombinedWorkbook.xlsx", FileFormat:=xlOpenXMLWorkbook
' Close the target workbook
targetWorkbook.Close SaveChanges:=True
' Display a message box to indicate the process is complete
MsgBox "The workbooks have been combined."
End Su
原文地址: https://www.cveoy.top/t/topic/hcbu 著作权归作者所有。请勿转载和采集!