Reputation: 2068
I have to excel sheet and, using vba, I would like to get a value in one of those, search it in the other one and return a correspondant value in the first sheet.
Given the sheet 1:
I would like to search the string I inserted in A5 in another sheet:
Sheet 2:
Once I found the match (A2 in this case), I would get the 'value' (in D2 in this case) and report it in the cell B5 of the Sheet1.
That's what I tried:
Dim rgFound As Range
Dim defVal As Range
Dim currParam As Range
Dim currParamDict As Range
For Each defVal In Range("B:B")
Set currParam = Cells(Range(defVal).Row, Range(defVal).Column - 1)
If currParam Is Nothing Then
Debug.Print "Name was not found."
End If
Set rgFound = Worksheets("Sheet2").Range("A:A").Find(currParam.value)
If rgFound Is Nothing Then
Debug.Print "Name was not found."
Else
Set currParamDict = Cells(Range(rgFound).Row, Range(rgFound).Column + 3)
defVal.value = currParamDict.value
End If
Next defVal
That's clearly wrong since the compiler gives me an error on Range at the line:
Set currParam = Cells(Range(defVal).Row, Range(defVal).Column - 1)
Upvotes: 0
Views: 408
Reputation: 23081
Try this
Sub x()
Dim rgFound As Range
Dim defVal As Range
Dim currParam As Range
Dim currParamDict As Range
With Worksheets("Sheet1")
For Each defVal In .Range("A2", .Range("A" & Rows.Count).End(xlUp)).Offset(, 1)
Set currParam = defVal.Offset(, -1)
If Len(currParam.Value) > 0 Then
Set rgFound = Worksheets("Sheet2").Range("A:A").Find(currParam.Value)
If rgFound Is Nothing Then
Debug.Print "Name was not found."
Else
Set currParamDict = rgFound.Offset(, 3)
defVal.Value = currParamDict.Value
End If
End If
Next defVal
End With
End Sub
Upvotes: 1