|
- 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
- Dim fileTotal As Long
- Dim rowRemainder As Long
-
- ' 设置源工作簿和工作表
- Set wsSource = Sheets("批量下拨")
-
- ' 获取源工作表中的最后一行
- lastRow = wsSource.Cells(wsSource.Rows.Count, "A").End(xlUp).Row
-
- ' 初始化计数器
- fileCounter = 1 ' 生成的文件数量
- rowCounter = 2 '复制数据的开始行数
- targetRow = 2 '粘贴数据的开始行数
- fileTotal = Int((lastRow - 1) / 20) '要复制的文件数量,当除不尽时,是实际数量-1
- rowRemainder = (lastRow - 1) Mod 20 ' 取得不足20行的剩余行数
-
- ' 获取当前日期字符串
- dateStr = Format(Now, "yyyy-mm-dd")
-
- ' 循环处理数据,每20行创建一个新工作簿
- Do While fileCounter <= fileTotal
- ' 创建新工作簿
- 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), wsTarget.Cells(targetRow + 19, wsSource.Columns.Count))
-
- ' 更新计数器和行号
- rowCounter = rowCounter + 20
- 'targetRow = targetRow + 20
- fileCounter = fileCounter + 1
- wbTarget.Save
- 'wbTarget.Close '需要自动关闭时,可以使用这一句
- Loop
-
- ' 如果最后一组数据不足20行,也需要复制
- If rowRemainder > 0 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, 1), wsSource.Cells(rowCounter + 19, wsSource.Columns.Count)).Copy _
- Destination:=wsTarget.Range(wsTarget.Cells(targetRow, 1), wsTarget.Cells(targetRow + 19, wsSource.Columns.Count))
- wbTarget.Save
- 'wbTarget.Close '需要自动关闭时,可以使用这一句
- End If
-
- ' 清理
- Set wsSource = Nothing
- Set wsTarget = Nothing
- Set wbTarget = Nothing
- Set wbSource = Nothing
- End Sub
复制代码 |
|