|
有一个表格,前3行是标题行,从第4行开始 每100行生成一个新的sheet,该如何操作
通过ai 写的vba代码报错,现在不知道 哪块有问题 请大神看看
- Sub SplitDataIntoSheets()
- Dim originalSheet As Worksheet
- Set originalSheet = ThisWorkbook.Worksheets("原始数据") ' 修改为您的原始数据工作表名称
-
- Dim rowCount As Long, row As Long
- Dim sheetCount As Long, startRow As Long
- Dim headers As Range, currentSheet As Worksheet
-
- ' 设置此变量以指定每个新sheet的数据行数(不含标题)
- Const maxRowsPerSheet As Long = 100
-
- rowCount = originalSheet.Cells(originalSheet.Rows.Count, 1).End(xlUp).row ' 获取原始数据的总行数
-
- ' 分割后的sheet数
- sheetCount = 0
-
- ' 从第4行开始,因为前三行是标题行
- For row = 4 To rowCount Step maxRowsPerSheet
- sheetCount = sheetCount + 1
- ' 创建新的工作表
- Set currentSheet = ThisWorkbook.Sheets.Add(After:=ThisWorkbook.Sheets))
- currentSheet.Name = "Sheet_" & sheetCount ' 命名新的工作表
-
- ' 复制标题行
- originalSheet.Rows("1:3").Copy Destination:=currentSheet.Rows("1:3")
-
- ' 计算当前块的起始和结束行
- startRow = row
- If startRow + maxRowsPerSheet - 1 <= rowCount Then
- ' 复制当前区块的数据
- originalSheet.Rows(startRow & ":" & startRow + maxRowsPerSheet - 1).Copy Destination:=currentSheet.Rows("4")
- Else
- ' 复制最后一个区块的数据(可能不满maxRowsPerSheet行)
- originalSheet.Rows(startRow & ":" & rowCount).Copy Destination:=currentSheet.Rows("4")
- End If
- Next row
-
- MsgBox sheetCount & " sheets have been created successfully.", vbInformation
- End Sub
复制代码
红色部分为 代码错误部分
|
|