Vbs 合并excel
时间: 2023-08-31 10:12:38 浏览: 187
可以使用 VBA 代码来合并多个 Excel 文件,以下是一个简单的示例:
```
Sub mergeExcelFiles()
Dim folderPath As String, selectedFiles() As String
Dim i As Integer
Dim wb As Workbook, ws As Worksheet
Dim destWb As Workbook, destWs As Worksheet
'选择要合并的文件夹
With Application.FileDialog(msoFileDialogFolderPicker)
.Title = "请选择要合并的文件夹"
If .Show Then folderPath = .SelectedItems(1)
End With
'获取文件夹中所有的 Excel 文件
selectedFiles = getExcelFiles(folderPath)
'新建一个工作簿,用于合并数据
Set destWb = Workbooks.Add
Set destWs = destWb.Sheets(1)
'遍历所有 Excel 文件,将数据合并到新工作簿中
For i = 0 To UBound(selectedFiles)
Set wb = Workbooks.Open(selectedFiles(i))
Set ws = wb.Sheets(1)
'将数据复制到新工作簿中
ws.UsedRange.Copy destWs.Cells(destWs.Rows.Count, 1).End(xlUp).Offset(1)
wb.Close False
Next i
'保存合并后的数据
destWb.SaveAs folderPath & "\合并后的数据.xlsx"
destWb.Close False
MsgBox "合并完成!"
End Sub
'获取指定文件夹中的所有 Excel 文件
Function getExcelFiles(folderPath As String) As String()
Dim files() As String, i As Integer, j As Integer
ReDim files(0)
i = 0
'获取文件夹中所有的文件
files = Split(CreateObject("WScript.Shell").Exec("cmd /c dir """ & folderPath & "\*.xlsx"" /b /s").StdOut.ReadAll, vbCrLf)
'筛选出 Excel 文件
For j = 0 To UBound(files)
If InStr(files(j), ".xlsx") > 0 Then
files(i) = files(j)
i = i + 1
ReDim Preserve files(i)
End If
Next j
ReDim Preserve files(i - 1)
getExcelFiles = files
End Function
```
这段代码会弹出一个对话框,让你选择要合并的 Excel 文件所在的文件夹。然后它会遍历该文件夹中的所有 Excel 文件,并将它们的数据合并到一个新的工作簿中。最后,它会将合并后的数据保存为一个新的 Excel 文件。你可以根据自己的需要修改代码中的路径和文件名。
阅读全文
相关推荐















