在另一个工作表中查找单元格值

时间:2019-07-17 08:41:41

标签: excel vba

我必须使用Excel,然后使用vba在其中一个中获取一个值,在另一个中搜索它,然后在第一张中返回一个对应的值。

给出工作表1:

enter image description here

我想在另一张纸上搜索我在A5中插入的字符串:

表格2:

enter image description here

一旦找到匹配项(在本例中为A2),我将获取“值”(在本例中为D2)并将其报告到Sheet1的单元格B5中。

这就是我尝试过的:

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

这显然是错误的,因为编译器在行上给我Range的错误:

Set currParam = Cells(Range(defVal).Row, Range(defVal).Column - 1)

1 个答案:

答案 0 :(得分:1)

尝试一下

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
相关问题