简体   繁体   中英

VBA Code that will iterate through each Row, and then copy/paste data from the origin sheet to the correct cell in the destination sheet

Currently I can achieve this task by these code chunks: Code

The problem I have is that the total number of rows can vary, and I do not want to have to go back and add more chunks of code for each additional product whenever that happens.

Is there a way I can loop through every row in the worksheet, and then have the data copy and paste to the correct destination cell like I currently have in the code above?

Not 100% sure how your worksheets look like, but you can find lastrow by:

Dim LastRow As Long
LastRow = Cells(Rows.Count, "U").End(xlUp).row

This will give you last row in column U. For me, based on your code, seems like you need to find last column

Option Explicit

Sub MyCopyPasteScript()
    
    Dim i
    
    Dim wsSource As Worksheet: Set wsSource = ThisWorkbook.Sheets("NANF Formatted")
    Dim wsDestination As Worksheet: Set wsDestination = ThisWorkbook.Sheets("NANF")

    Dim lastColumn As Long
    lastColumn = wsSource.Cells(2, wsSource.Columns.Count).End(xlToLeft).Column
    
    For i = 2 To lastColumn
        If wsSource.Cells(2, i) = "" Then
            'Do something here if cell is empty
        Else
            'Copy data to another worksheet
            wsSource.Cells(2, i).Copy
            wsDestination.Cells(2, i - 5).PasteSpecial 'You can use other Paste options
            'Also it copies from starting column H and pasts to starting from column C, by doing some math 'i-5'
        End If
    Next i

End Sub

I have covered here your first portion, you can add more functionality to code above.


Or maybe even something like this:

Option Explicit

Sub CopyPaste()

    Dim lastRow As Long   
    Dim wsSource As Worksheet: Set wsSource = ThisWorkbook.Sheets("NANF Formatted")
    Dim wsDestination As Worksheet: Set wsDestination = ThisWorkbook.Sheets("NANF")
    
    lastRow = wsSource.Cells(wsSource.Rows.Count, 8).End(xlUp).Row
    
    'Copy range
    wsSource.Range("H2:N2" & lastRow).Copy
    
    wsDestination.Range("C2").PasteSpecial

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