Sub MergeData() Dim FilePath As String Dim FileName As String Dim SheetName As String Dim DestFileName As String Dim DestSheetName As String Dim LastRow As Long Dim DestLastRow As Long Dim i As Integer Dim j As Integer '设置源文件夹路径和目标文件夹路径 FilePath = "C:\SourceFolder\" DestFilePath = "C:\DestFolder\" '循环遍历源文件夹下的所有文件 FileName = Dir(FilePath) Do While FileName <> "" '打开源文件 Workbooks.Open (FilePath & FileName) '获取源文件名和表格名 SheetName = ActiveWorkbook.Sheets(1).Name '循环遍历源表格中的所有行 For i = 1 To 9405 '获取当前行的地点名称 PlaceName = ActiveWorkbook.Sheets(1).Cells(i, 1).Value '在目标文件中查找该地点名称对应的表格 DestFileName = DestFilePath & PlaceName & ".xlsx" If Dir(DestFileName) = "" Then '如果目标文件不存在,则新建该文件,并在第一行写入表头 Workbooks.Add ActiveSheet.Name = SheetName ActiveWorkbook.SaveAs DestFileName ActiveWorkbook.Close Workbooks.Open (DestFileName) DestLastRow = 1 For j = 1 To 10 ActiveWorkbook.Sheets(1).Cells(DestLastRow, j).Value = ActiveWorkbook.Sheets(1).Cells(1, j).Value Next j Else '如果目标文件已存在,则打开该文件,并在最后一行写入当前行的数据 Workbooks.Open (DestFileName) DestLastRow = ActiveWorkbook.Sheets(1).UsedRange.Rows.Count + 1 End If '将当前行的数据写入目标文件中对应的表格中 For j = 1 To 10 ActiveWorkbook.Sheets(1).Cells(DestLastRow, j).Value = ActiveWorkbook.Sheets(1).Cells(i, j).Value Next j ActiveWorkbook.Save ActiveWorkbook.Close Next i '关闭源文件 Workbooks(FileName).Close '获取下一个文件名 FileName = Dir Loop End Sub这段代码中SaveAs作用于对象'_Workbook'时失败,更改
时间: 2024-02-10 14:14:18 浏览: 68
C#中图片.BYTE[]和base64string的转换方法
SaveAs的作用对象应该是Workbooks,而不是ActiveWorkbook,因此应该将代码中的以下行:
ActiveWorkbook.SaveAs DestFileName
改为:
Workbooks(DestFileName).SaveAs DestFileName
这样就可以正确保存目标文件了。
阅读全文