如何在vba中选择和复制excel的第一行和最后一行?

时间:2016-05-11 15:07:17

标签: vba excel-vba excel

我想选择并复制Excel工作表中的前3行和最后一行,但在我的代码下面Selection.Copy行会出错。

Sub SaveLastLine()
    Dim WB As Workbook, filename As String

    Application.ScreenUpdating = False
    Application.DisplayAlerts = False

    Range("B1").Select
    Selection.End(xlDown).Select
    Union(Range("1:3"), Range(Selection, Selection.End(xlToRight))).Select

    Selection.Copy
    Workbooks.Add
    ActiveSheet.Paste
End Sub

请有人帮助我。

2 个答案:

答案 0 :(得分:2)

使用选定的范围可能是您的问题。 Kellsens为您提供了一个解决方案,首先复制前三行,然后将最后一行复制到新工作表中。

如果要一次性完成所有操作,可以先定义范围,然后将该范围的内容复制到新工作簿。像这样:

Sub SaveLastLine()

    Dim WB As Workbook
    Dim myRange As Range

    'copy the content
        Set myRange = Union(Range(Range("B1:B3"), Range("B1:B3").End(xlToRight)), _
                            Range(Range("B1").End(xlDown), Range("B1").End(xlDown).End(xlToRight)))
        myRange.Copy

    'paste the content
        Set WB = Workbooks.Add
        WB.ActiveSheet.Range("A1").PasteSpecial

End Sub

答案 1 :(得分:1)

创建新工作簿时,没有要粘贴的活动表,这就是错误原因。您可以将新工作簿实例化为声明的变量Wb。 考虑到您的数据以“B1”开头,并且考虑到您的新工作表将有4行,我对您的代码进行了一些修改:

Sub SaveLastLine()
    Dim wb As Workbook
    Dim ws As Worksheet
    Dim filename As String
    Dim lastCol As Integer
    Dim lastRow As Integer

    Application.ScreenUpdating = False
    Application.DisplayAlerts = False

    Set ws = ActiveSheet ' Here I instantiate the active worksheet
    Set wb = Workbooks.Add ' Here I instantiate the new workbook

    lastCol = ws.Range("B1").End(xlToRight).Column
    lastRow = ws.Range("B1").End(xlDown).Row

    ws.Range(ws.Cells(1, 2), ws.Cells(3, lastCol)).Copy wb.Worksheets(1).Range("B1") ' Here I copy the first 3 rows and paste in the first worksheet of your new workbook
    ws.Range(ws.Cells(lastRow, 2), ws.Cells(lastRow, lastCol)).Copy wb.Worksheets(1).Range("B4") ' Here I copy the last row and paste

    filename = "yourfilename.xlsx"
    wb.SaveAs filename

    Application.ScreenUpdating = True
    Application.DisplayAlerts = True

End Sub