用vbs 实现将一个目录下的同格式excel表合并为一个工作表
时间: 2023-03-26 09:03:50 浏览: 162
你好,这个问题可以通过编写 VBA 宏来实现。以下是一个示例代码:
Sub MergeExcelFiles()
Dim path As String, thisWB As String, targetWB As Workbook
Dim ws As Worksheet, i As Integer, j As Integer
Dim row As Long, col As Long
'设置目标工作簿
Set targetWB = Workbooks.Add(xlWBATWorksheet)
row = 1
col = 1
'选择要合并的文件夹
path = Application.GetOpenFilename("Excel Files (*.xls*), *.xls*", , "Select Excel Files to Merge", , True)
'循环遍历文件夹中的所有 Excel 文件
If path <> False Then
thisWB = ActiveWorkbook.Name
Application.ScreenUpdating = False
Application.DisplayAlerts = False
i = 1
Do While path <> False
Set ws = Workbooks.Open(path:=path).Worksheets(1)
If i = 1 Then
'如果是第一个文件,将第一个工作表复制到目标工作簿
ws.Copy after:=targetWB.Worksheets(targetWB.Worksheets.Count)
Else
'如果不是第一个文件,将第一个工作表之外的所有工作表复制到目标工作簿
For j = 2 To ws.Worksheets.Count
ws.Worksheets(j).Copy after:=targetWB.Worksheets(targetWB.Worksheets.Count)
Next j
End If
i = i + 1
path = Application.GetOpenFilename("Excel Files (*.xls*), *.xls*", , "Select Excel Files to Merge", , True)
Loop
'关闭所有打开的工作簿
Workbooks(thisWB).Activate
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End If
End Sub
希望这可以帮到你。
阅读全文