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这段代码中下标越界,更改
时间: 2024-03-19 13:42:06 浏览: 100
在循环遍历源表格中的所有行之前,应该先获取源表格中的最后一行,以便在循环中使用。因此,应该将代码中的以下行:
For i = 1 To 9405
改为:
LastRow = ActiveWorkbook.Sheets(1).UsedRange.Rows.Count
For i = 2 To LastRow
这样就可以正确获取源表格中的最后一行,并避免下标越界的问题。同时,在循环中,应该将i的初始值改为2,以跳过表头行。
阅读全文