如何将VLOOKUP中的值返回到单元格?

时间:2013-10-06 10:56:58

标签: vba

我有以下Vlookup代码。该函数工作正常,但找到的值不会显示在单元格中。但是,如果我有一个使用过的Msgbox函数,则会显示找到的值。问题是在单元格中没有捕获VLOOKUP结果吗?

Sub Example_of_Vlookup()
Dim lookFor As Range
Dim rng As Range
Dim col As Integer
Dim found As String
Dim lastrowrange As Long
Dim area As Range
lastrowrange = [A65536].End(xlUp).Row
Set lookFor = Sheets("Sheet2").Range("b2")
Set rng = Sheets("Sheet2").Columns("t:u")
Set taxRange = Range("f2", Cells(lastrowrange, 22))
col = 2

On Error Resume Next
For i = 1 To lastrowrange
found = Application.VLookup("B2", "T1:U4", 2, True)
If IsError(found) Then
MsgBox lookFor & " not found"
Else

area.Cells(i, 2).Value = found
End If
Next i
On Error GoTo 0
End Sub

2 个答案:

答案 0 :(得分:1)

您未将范围“area”设置为等于任何内容,因此此行不会正确显示您的答案:

area.Cells(i, 2).Value = found

area.Cells(i,2).value更改为sheets("Sheet2").Cells(i,2).value或您希望答案显示的位置。或者,如果要使用area.cells,请将区域设置为等于。

答案 1 :(得分:1)

  

想法很简单 - 我在列B中有国名.Intion是拉出国家所属的区域 - 我的查找值在列S(国家)和T(区域)中,并在F列中显示结果 - Sayanth Sasidharan 25分钟前

如果根据您的解释我的理解是正确的,那么您不需要使用循环。让Excel做肮脏的工作;)你最终会得到更少的代码。

假设您的工作表看起来像这样

enter image description here

<强>逻辑

  1. 找到Col B的最后一行
  2. Vlookup中一次性插入F1:F & LastRow公式
  3. 将它们转换为值。
  4. <强>代码

    Option Explicit
    
    Sub Example_of_Vlookup()
        Dim ws As Worksheet
        Dim lRow As Long
    
        Set ws = ThisWorkbook.Sheets("Sheet2")
    
        With ws
            lRow = .Range("B" & .Rows.Count).End(xlUp).Row
    
            '~~> =IF(ISERROR(VLOOKUP(B1,S:T,2,0)),"",VLOOKUP(B1,S:T,2,0))
            .Range("F1:F" & lRow).Formula = _
            "=IF(ISERROR(VLOOKUP(RC[-4],C[13]:C[14],2,0)),"""",VLOOKUP(RC[-4],C[13]:C[14],2,0))"
    
            .Range("F1:F" & lRow).Value = .Range("F1:F" & lRow).Value
        End With
    End Sub
    

    <强>结果:

    enter image description here