I need a VBA code to count the number rows, which varies from ss to ss, return that number and copy and paste that row and all other columns

后端 未结 1 1144
眼角桃花
眼角桃花 2021-01-24 06:57

I have vba question I have been trying to find the answer for for a long time. I have numerous spreadsheets from numerous clients that I run macro\'s on, I\'m new to coding and

相关标签:
1条回答
  • 2021-01-24 07:30

    This should give you the last row containing data:

    ActiveSheet.UsedRange.Rows.Count
    

    This will give you the last row in a specific column:

    Range("B" & Rows.Count).End(xlUp).Row
    

    here is an example of how I can copy every row in the first three columns of a worksheet

    Sub Example()
        Dim LastRow As Long
    
        LastRow = ActiveSheet.UsedRange.Rows.Count
        Range(Cells(1, 1), Cells(LastRow, 3)).Copy Destination:=Sheet2.Range("A1")
    End Sub
    

    You have to be careful as there are some caveats to both methods.

    ActiveSheet.UsedRange may include cells that do not have any data if the cells were not cleaned up properly.

    Range("A" & Rows.Count).End(xlUp).Row will only return the number of rows in the specified column.

    Rows(Rows.Count).End(xlUp).Row will only return the number of rows in the first column.

    Edit Added an example
    Edit2 Changed the example to be a bit more clear

    For this example lets say we have this data
    enter image description here

    You could copy any other column down to the number of rows in column A using this method:

    Sub Example()
        Dim Col as Integer
        Col = Columns("C:C").Column
    
        'This would copy all data from C1 to C5
        'Cells(1, Col) = Cell C1, because C1 is row 1 column 3
        Range(Cells(1, Col), Cells(Range("A" & Rows.Count).End(xlUp).Row, Col)).Copy Destination:=Sheet2.Range("A1")
    End Sub
    

    The end result would be this:
    enter image description here

    0 讨论(0)
提交回复
热议问题