参考不同表格的最后一行

时间:2016-05-16 20:55:09

标签: excel vba excel-vba

目前我在Sheet2上有这个

Range("A2").Select
Selection.AutoFill Destination:=Range("A2:A1001")
Range("A2:A1001").Select
Range("B2").Select
Selection.AutoFill Destination:=Range("B2:B1001")
Range("B2:B1001").Select
Range("C2").Select
Selection.AutoFill Destination:=Range("C2:C1001")
Range("C2:C1001").Select
Range("D2").Select
Selection.AutoFill Destination:=Range("D2:D1001")
Range("D2:D1001").Select
Range("E2").Select
Selection.AutoFill Destination:=Range("E2:E1001")
Range("E2:E1001").Select
Range("G2").Select
Selection.AutoFill Destination:=Range("G2:G1001")
Range("G2:G1001").Select
Range("H2").Select
Selection.AutoFill Destination:=Range("H2:H1001")
Range("H2:H1001").Select
Range("I2").Select
Selection.AutoFill Destination:=Range("I2:I1001")
Range("I2:I1001").Select
Range("J2").Select
Selection.AutoFill Destination:=Range("J2:J1001")
Range("J2:J1001").Select
Range("K2").Select
Selection.AutoFill Destination:=Range("K2:K1001")
Range("K2:K1001").Select

我没有目标范围A2到A1001,而是想让A2与sheet1在同一个最后一行,例如,如果在sheet1中,最后一行是第147行,我希望代码填写Selection.AutoFill Destination:=Range("A2:A147")

我不知道如何做到这一点。

由于

2 个答案:

答案 0 :(得分:2)

这对你有用......

Sub LastRowAutofill()
    On Error Resume Next
    Dim wsSheet1 As Worksheet: Set wsSheet1 = Worksheets("Sheet1")
    Dim LastRow As Long
    LastRow = wsSheet1.Columns(1).Find("*", LookIn:=xlValues, SearchDirection:=xlPrevious).Row

    Dim i As Long
    With Worksheets("Sheet2")
        For i = 1 To 11
            If i <> 6 Then .Cells(2, i).AutoFill Destination:=.Range(.Cells(2, i), .Cells(LastRow, i))
        Next i
    End With

End Sub

如果您想要整个sheet1中的最后一行,您可以使用以下内容:

    LastRow = wsSheet1.UsedRange.Find("*", LookIn:=xlValues, SearchDirection:=xlPrevious).Row

答案 1 :(得分:0)

假设您的原始数据在Sheet1上并且您要复制到Sheet2,请按照以下方式进行操作:

Dim intLastrow As Integer

intLastrow = Sheets("Sheet1").Cells(Rows.Count, "A").End(xlUp).Row
Sheets("Sheet2").Range("A2").Select
Selection.AutoFill Destination:=Range(cells(2,"A"),cells(intLastrow, "A"))
Sheets("Sheet2").Range(Cells(2, "A"), Cells(intLastrow, "A")).Select

intLastrow = Sheets("Sheet1").Cells(Rows.Count, "B").End(xlUp).Row    
Sheets("Sheet2").Range("B2").Select
Selection.AutoFill Destination:=Range(cells(2,"B"),cells(intLastrow, "B"))
Sheets("Sheet2").Range(Cells(2, "B"), Cells(intLastrow, "B")).Select