将大型Excel文件复制到500行较小的文件中

时间:2015-07-29 15:02:09

标签: excel vba

我在Excel中有以下几乎的vba代码。我遇到的问题是" firstrow"并没有增加。第一个文件将包含1-501行,第二个文件将包含1-1001(我希望它包含第1行和第502-1001行)。我确定这是一个小问题,但我已经盯着它看了一段时间,似乎无法弄清楚什么是错的。一些帮助真的很棒!

Sub FiveHundredLineCopy()

Dim Firstrow As Integer
Dim Lastrow As Integer
Dim Copyrange As String
Dim Startcell As String
Dim Month, Year As String

Firstrow = 2    'Starts on row 2 to exclude header
Lastrow = Firstrow + 499
Month = Nov 'Month of Clinic for filename
Year = 2014 'Year of Clinic for filename
Filenumber = 1  'First file in sequence

Let Startcell = "A" & Firstrow
Let Copyrange = "A" & Firstrow & ":" & "BZ" & Lastrow       'Only copying through column BZ

Do While Range(Startcell) <> ""
    Range("A1:BZ1", Copyrange).Copy    'Includes A1:BZ1 to copy header row as well
    Set NewBook = Workbooks.Add
    NewBook.Worksheets("Sheet1").Range("A1").PasteSpecial Paste:=xlPasteAllUsingSourceTheme
    NewBook.SaveAs Filename:=Range("AJ2").Text & "_Sams_Apex_" & Month & " " & Year & "_File " & Filenumber & ".csv", FileFormat:=xlCSV
    NewBook.Close Savechanges:=False

    Firstrow = Firstrow + 500
    Lastrow = Firstrow + 499
    Filenumber = Filenumber + 1
    Let Startcell = "A" & Firstrow
    Let Copyrange = "A" & Firstrow & ":" & "BZ" & Lastrow
Loop

End Sub

2 个答案:

答案 0 :(得分:0)

Range(Cell1,Cell2)选择从Cell1到Cell2的单元格。您可以先复制并粘贴标题,然后复制并粘贴您想要的Copyrange。

答案 1 :(得分:0)

您正在将Copyrange从标题行扩展到要复制的最后一行。如上所述,您可以运行两个操作或隐藏已经复制的行。

Do While Range(Startcell) <> ""
    Range("A1:BZ1", Copyrange).Copy    'Includes A1:BZ1 to copy header row as well
    Set NewBook = Workbooks.Add
    NewBook.Worksheets("Sheet1").Range("A1").PasteSpecial Paste:=xlPasteAllUsingSourceTheme
    NewBook.SaveAs Filename:=Range("AJ2").Text & "_Sams_Apex_" & Month & " " & Year & "_File " & Filenumber & ".csv", FileFormat:=xlCSV
    NewBook.Close Savechanges:=False

    'hide the ones already copied. hidden rows will not be copied to the new location
    copyrange.resize(copyrange.rows.count - 1, copyrange.columns.count).offset(1, 0).entirerow.hidden = true

    Firstrow = Firstrow + 500
    Lastrow = Firstrow + 499
    Filenumber = Filenumber + 1
    Let Startcell = "A" & Firstrow
    Let Copyrange = "A" & Firstrow & ":" & "BZ" & Lastrow
Loop

在拆分操作完成后,不要忘记取消隐藏所有行。