Sub SplitDataIntoNewWorkbooks() Dim wbSource As Workbook Dim wsSource As Worksheet Dim wbTarget As Workbook Dim wsTarget As Worksheet Dim lastRow As Long Dim rowCounter As Long Dim fileCounter As Long Dim targetRow As Long Dim dateStr As String Dim targetName As String '设置源工作簿和工作表 Set wbSource = Workbooks("批量下拨20240731") Set wsSource = wbSource.Sheets("批量下拨") '获取源工作表中的最后一行 lastRow = wsSource.Cells(wsSource.Rows.Count,"A").End(xlUp).Row '初始化计数器 fileCounter = 1 rowCounter = 1 targetRow = 2 '获取当前日期字符串 dateStr = Format(Now, "yyyy-mm-dd") '循环处理数据,每20行创建一个新工作簿 Do While rowCounter <= lastRow ' 创建新工作簿 Set wbTarget = Workbooks.Add Set wsTarget = wbTarget.Sheets(1) ' 设置新工作簿的名称为当前日期加上序号 targetName = "批量下拨_" & dateStr & "_" & fileCounter &".xlsx" wbTarget.SaveAs Filename:=ThisWorkbook.Path& "\\" & targetName ' 复制第一行到新工作簿 wsSource.Rows(1).Copy Destination:=wsTarget.Rows(1) ' 复制后续的20行数据到新工作簿 wsSource.Range(wsSource.Cells(rowCounter, 1), wsSource.Cells(rowCounter+ 19, wsSource.Columns.Count)).Copy _ Destination:=wsTarget.Range(wsTarget.Cells(targetRow, 1)) ' 更新计数器和行号 rowCounter = rowCounter + 20 targetRow = targetRow + 20 fileCounter = fileCounter + 1 Loop '如果最后一组数据不足20行,也需要复制 If rowCounter - 20 < lastRow Then Set wbTarget = Workbooks.Add Set wsTarget = wbTarget.Sheets(1) ' 设置新工作簿的名称为当前日期加上序号 targetName = "批量下拨_" & dateStr & "_" & fileCounter &".xlsx" wbTarget.SaveAs Filename:=ThisWorkbook.Path & "\\" &targetName ' 复制第一行到新工作簿 wsSource.Rows(1).Copy Destination:=wsTarget.Rows(1) ' 复制剩余的数据到新工作簿 wsSource.Range(wsSource.Cells(rowCounter - 20, 1),wsSource.Cells(lastRow, wsSource.Columns.Count)).Copy _ Destination:=wsTarget.Range(wsTarget.Cells(targetRow, 1)) End If '清理 Set wsSource = Nothing Set wsTarget = Nothing Set wbTarget = Nothing Set wbSource = Nothing End Sub
|