简体   繁体   中英

How to loop for multiple columns in VBA

I have this below code to copy data from one sheet and to paste it onto another sheet. However, i need to paste about 100 columns of data. How do i get my loop to run 100 times so i dont have to copy this code down a 100 times?

Thanks

Sub Macro1()

    Dim lastrow as long, erow as long

    lastrow = Sheet4.Cells(Rows.Count, 1).End(xlUp).Row

    For i = 2 to lastrow
        Sheets4.cells(i,1).Copy
        erow = Sheet7.Cells(Rows.Count, 1).End(xlUp).Offset(1,0).Row

        Sheet4.Paste Sheet7.Cells(erow,1)

        Sheet4.Cells(i,2).Copy
        Sheet4.Paste Sheet7.Cells(erow,2)

You do not say anything and I cannot stay, anymore... If you do not need to copy format, try the next code. It will copy all columns of Sheet4 starting from their second row, to the first empty row of Shee77 . It is much faster than what you tried, using an array and drop all content at once...

Sub Macro1_bis()
 Dim arrSh4 As Variant, sh7Row As Long
 arrSh4 = Sheet4.UsedRange.Offset(1).value
 sh7Row = Sheet7.Range("A" & Cells.Rows.Count).End(xlUp).Row + 1
 Sheet7.Range("A" & sh7Row).Resize(UBound(arrSh4, 1), UBound(arrSh4, 2)).value = arrSh4
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM