Forum Discussion

johnellis1971200's avatar
johnellis1971200
Copper Contributor
Jan 26, 2024
Solved

Copying Data from Another Excel Workbook Based on Criteria -- Part 2 :)

Microsoft Excel's Workbook 1 has data in cell A3 and J3. Likewise, Workbook 2 has data in cells A2 and B2. I need to devise (or modify within a VBA script) a macro to copy data from A2 in Workbook ...
  • djclements's avatar
    Jan 28, 2024

    johnellis1971200 Try the procedure in reverse, where you loop through the rows in the target worksheet instead:

     

    Sub CopyDataBetweenWorkbooks()
    'Declare variables
        Dim sourceWorkbook As Workbook, targetWorkbook As Workbook
        Dim sourceSheet As Worksheet, targetSheet As Worksheet
        Dim lastRow As Long, i As Long, rowId As Variant
    
    'Set references to the source and target workbooks
        Set sourceWorkbook = Workbooks("Payroll Processing.xlsx")
        Set targetWorkbook = Workbooks("Job Journals.xlsx")
    
    'Set references to the source and target worksheets
        Set sourceSheet = sourceWorkbook.Sheets(1)
        Set targetSheet = targetWorkbook.Sheets(1)
    
    'Find the last row with data in the Employee ID column of the target worksheet
        lastRow = targetSheet.Cells(targetSheet.Rows.Count, 10).End(xlUp).Row
    
    'Loop through each row in the target worksheet
        For i = 3 To lastRow
        ' find the matching row in the source worksheet based on employee ID
            rowId = Application.Match(targetSheet.Cells(i, 10).Value, sourceSheet.Columns(2), 0)
        
        ' if a match is found, copy data from source to target worksheet
            If Not IsError(rowId) Then targetSheet.Cells(i, 1).Value = sourceSheet.Cells(rowId, 1).Value
        Next i
    End Sub

     

    Note: Application.Match was used in this example instead of the Range.Find method.

Resources