根据行数创build单独的工作表

我知道这已经被讨论,我已经从Stackoverflow上的几个不同的post得到了下面的代码。 我的问题是,如果列“A”的行数不等于硬编码数(rowsPerSheet = 10),它会将额外的行添加回原始页面。 如果我有35行,我会得到3个工作表2和3的工作表是正确的,但工作表1将有行1-10 +行31-35)。 我应该改变什么? 请原谅多余的代码,我只是想确保我把答案放在正确的地方。

Sub SaveSheets() Application.EnableEvents = False Dim nUserInput As String Dim wsMasterSheet As Excel.Worksheet Dim wb As Excel.Workbook Dim sheetCount As Integer Dim rowCount As Integer Dim rowsPerSheet As Integer nUserInput = InputBox("Enter Job Number:", "Collect User Input") Set wsMasterSheet = ActiveSheet Set wb = ActiveWorkbook rowsPerSheet = 10 rowCount = Application.CountA(Sheets(1).Range("A:A")) sheetCount = Round(rowCount / rowsPerSheet, 0) Dim i As Integer For i = 1 To sheetCount - 1 Step 1 With wb 'Add new sheet .Sheets.Add after:=.Sheets(.Sheets.Count) wsMasterSheet.Range("A1:M1").EntireRow.Copy Destination:=Sheets(.Sheets.Count).Range("A1").End(xlUp) wsMasterSheet.Range("A2" & ":M" & (rowsPerSheet + 1)).EntireRow.Cut Destination:=Sheets(.Sheets.Count).Range("A" & Rows.Count).End(xlUp).Offset(1) wsMasterSheet.Range("A2" & ":M" & (rowsPerSheet + 1)).EntireRow.Delete ActiveSheet.Name = "Valves " + CStr(((.Sheets.Count - 1) * rowsPerSheet + 1)) End With Next wsMasterSheet.Name = "Valves End" Application.EnableEvents = True Dim strPath As String Dim ws As Worksheet Application.ScreenUpdating = False strPath = "\\Server Name\Engineering\iPortal Valves\" For Each ws In ThisWorkbook.Sheets ws.Copy Workbooks(Workbooks.Count).Close True, strPath & nUserInput & "_" & ws.Name & ".xlsx" Next Application.Quit ActiveWorkbook.Close SaveChanges:=True Application.ScreenUpdating = True End Sub 

试图通过这个想法,我想知道是否可以添加使用

 lastRow = Sheet1.UsedRange.Row + Sheet1.UsedRange.Rows.Count - 1 

在非编码术语中:

如果lastRow大于RowsPerSheet且小于(2 * RowsPerSheet – 1),则RowsPerSheet =(lastRow – RowsPerSheet)。

RowsPerSheet是否需要“昏暗”以允许代码覆盖硬性值? 如果我正确理解了代码处理过程,如果复位RowsPerSheet的代码是“For / Next”,那么当macros再次运行时,硬编码的编号将保持不变。

这里的其他问题是:1)代码如何编写?2)代码在哪里?

我已经修改了上面的代码,使我能够工作。 原始工作表根据rowPerSheet拆分为单独的工作表,并创build单个文件并保存到指定的位置。

感谢所有在Stackoverflow上发布post的人,所有的代码都被从各个post中提取出来。