将特定行从工作簿复制到x数量的新工作簿中(每行一个),仅粘贴为格式/值

时间:2019-02-27 15:10:06

标签: excel vba

VBA入门。 我正在尝试做的事情:

  • 复制当前工作表中的前5行_'x'行,并粘贴到新工作簿中
  • 新工作簿应保存在同一目录中
  • 对于前5个以下的每一行都应重复此操作,即第1-5 + 6行,第1-5 + 7行,第1-5 + 8行等。
  • 将行粘贴到新工作簿中时,我不想复制公式,而只是复制格式和值

这是我到目前为止所拥有的:

Sub CommandButton1_Click()

    Dim MyBook As Workbook, newBook As Workbook
    Dim FileNm As String

    Set MyBook = ThisWorkbook

    FileNm = ThisWorkbook.Path & "\" & "TEST-BOOK.xlsx"
    Set newBook = Workbooks.Add

    With newBook
        MyBook.Sheets("Sheet1").Rows("1:5").Copy .Sheets("Sheet1").Rows("1")

        'Save new wb
        .SaveAs Filename:=FileNm, CreateBackup:=False

        .Close Savechanges:=False
    End With

End Sub

它会复制1-5行,但我不知道如何添加动态多余的行-它还会复制所有公式并将其嵌入。假设文件名也必须处于某种循环中? 谢谢。

1 个答案:

答案 0 :(得分:1)

希望这会有所帮助,

Sub CommandButton1_Click()

    Dim wb As Workbook, FileNm As String, LastRow As Long, Headers As Range, wbTemp As Workbook, i As Long

    Application.EnableEvents = False
    Application.Calculation = xlCalculationManual
    Application.ScreenUpdating = False

    Set wb = ThisWorkbook

    'lets suppose your data is in the first worksheet of your book
    With wb
        LastRow = .Sheets(1).Cells(.Sheets(1).Rows.Count, 1).End(xlUp).Row - 5 'this is to count how many rows you've got
        Set Headers = .Sheets(1).Rows("1:5") 'set the headers to copy them every iteration
    End With

    'copy each row + headers in a new workbook
    For i = 1 To LastRow
        FileNm = wb.Path & "\" & "TEST-BOOK" & i & ".xlsx" 'add the i to number every workbook from 1 to extra rows you have
        Set wbTemp = Workbooks.Add 'add a new workbook
        Headers.Copy 
        wbTemp.Sheets(1).Rows(1).PasteSpecial xlPasteValues 'paste the headers
        wb.Sheets(1).Rows(5 + i).Copy 
        wbTemp.Sheets(1).Rows(6).PasteSpecial xlPasteValues 'copy the next row in the iteration
        wbTemp.SaveAs FileNm
        wbTemp.Close
        Set wbTemp = Nothing
    Next i

    Application.EnableEvents = True
    Application.Calculation = xlCalculationAutomatic
    Application.ScreenUpdating = True

End Sub