I am trying to write a macro to compare two ranges, Rng1 and Rng2 in excel. Rng1, ("f2:f15"), contains target numbers which are being used. Rng2, ("a2:a91"), contains the numbers for all possible targets. The three columns to the right of Rng2, ("b2:b91"), ("c2:c91"), and ("d2:d91"), contain the x, y, and z coordinate values associated with each target number. What I would like this macro to do is to populate the 3 columns to the right of Rng1, ("g2:g15"), ("h2:h15"), and ("i2:i15") with the coordinate values of the target number found in Rng1. The following code I have written is retuning "Run time error '13', type mismatch".
Sub macro()
Dim Rng1 As Range, Rng2 As Range, Cell1 As Range, Cell2 As Range
Set Rng1 = Range("f2:f15")
Set Rng2 = Range("a2:a91")
For i = 1 To Rng1
For j = 1 To Rng2
For Each Cell1 In Rng1(i)
For Each Cell2 In Rng1(j)
If Cell1.Value = Cell2.Value Then
'cell1.Offset(0, 1) = cell2.Offset(0, 1)
'cell1.Offset(0, 1) = cell2.Offset(0, 1)
'cell1.Offset(0, 1) = cell2.Offset(0, 1)
Cells(2 + i, 7) = Cells(2 + j, 2)
Cells(2 + i, 8) = Cells(2 + j, 3)
Cells(2 + i, 9) = Cells(2 + j, 4)
End If
Next Cell2
Next Cell1
Next j
Next i
End Sub
Thanks!
Based on your description I think this is what you want
Sub Demo()
Dim Rng1 As Range, Rng2 As Range, Cell1 As Range
Dim i As Variant
Set Rng1 = Range("f2:f15")
Set Rng2 = Range("a2:a91")
' Loop over the cells you want to add data for
For Each Cell1 In Rng1
' locate current value in range 2
i = Application.Match(Cell1.Value, Rng2, 0)
If Not IsError(i) Then
' if found copy offset data
Cell1.Offset(0, 1) = Rng2.Cells(i, 2)
Cell1.Offset(0, 2) = Rng2.Cells(i, 3)
Cell1.Offset(0, 3) = Rng2.Cells(i, 4)
End If
Next
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.