Excel – Pulling data from another workbook using VBA in excel

excelvba

I have a range of unique project IDs in 2 workbooks. One of the workbooks doesn't contain the details of the projects, while the other workbook contains all of the project details.

I want to pull out the information from one workbook according to the unique project ID found in the other workbook. I have tried coding this, but it only works for extracting the data from the external workbook for the one with the project ID. I need it to work to extract the data for a range of project IDs given in a column.

This is the code I currently have:

Sub AAA()

    If Workbooks("Source.xlsm").Sheets("Sheet2").Range("A2").Value = Workbooks("Target.xlsm").Sheets("Sheet1").Range("A2").Value Then
        Workbooks("Source.xlsm").Sheets("Sheet2").Range("B2").Value = Workbooks("Target.xlsm").Sheets("Sheet1").Range("C2").Value
    End If

End Sub

This code only works for a particular cell, but I would need to extract a range of data from a range of project IDs located in the external workbook. What can I do to get this to work?

Best Answer

As per your question you need to add one more loop try this

Sub copydata()
Dim i As Long, j As Long
Dim targetlastrow As Long, sourcelstrow As Long
Dim Sourcelastcol As Long
Dim source As Worksheet
Dim target As Worksheet

Set source = Workbooks("Source.xlsm").Sheets("Sheet2")
Set target = Workbooks("Target.xlsm").Sheets("Sheet1")

targetlastrow = target.Range("A" & target.Rows.Count).End(xlUp).Row
sourcelstrow = source.Range("A" & source.Rows.Count).End(xlUp).Row
Sourcelastcol = source.Cells(2, source.Columns.Count).End(xlToLeft).Column

For i = 2 To targetlastrow
    For j = 2 To sourcelstrow
        If target.Range("A" & i).Value = source.Range("A" & j) Then
            source.Activate
            source.Range("B" & j).Select
            Range(ActiveCell, ActiveCell.Offset(0, Sourcelastcol)).Copy
            target.Range("B" & i).PasteSpecial
        End If
    Next j
Next i
End Sub
Related Topic