在vba中编写VLOOKUP函数

时间:2011-04-06 13:54:31

标签: excel vba

我正在尝试使用我的vba代码中的VLOOKUP函数在表数组中的电子表格中查找值。我不知道怎么写得正确。

以下是包含所有引用的正常VLOOKUP公式:

=VLOOKUP(DATA!AN2,DATA!AA9:AF20,5,FALSE)

6 个答案:

答案 0 :(得分:44)

你试过了吗?

Dim result As String 
Dim sheet As Worksheet 
Set sheet = ActiveWorkbook.Sheets("Data") 
result = Application.WorksheetFunction.VLookup(sheet.Range("AN2"), sheet.Range("AA9:AF20"), 5, False)

答案 1 :(得分:17)

如何使用:

result = [VLOOKUP(DATA!AN2, DATA!AA9:AF20, 5, FALSE)]

请注意 []

答案 2 :(得分:6)

请在Vlookup找到以下代码:

Function vlookupVBA(lookupValue, rangeString, colOffset)
vlookupVBA = "#N/A"
On Error Resume Next
Dim table_lookup As range
Set table_lookup = range(rangeString)
vlookupVBA = Application.WorksheetFunction.vlookup(lookupValue, table_lookup, colOffset, False)
End Function

答案 3 :(得分:2)

作为Tim Williams suggested,如果找不到查找值,则使用Application.VLookup不会抛出错误(与Application.WorksheetFunction.VLookup不同)。

如果希望查找在找不到匹配项时返回默认值,并且为了避免对列号进行硬编码 - 相当于公式中的IFERROR(VLOOKUP(what, where, COLUMNS(where), FALSE), default),则可以使用以下函数:

Private Function VLookupVBA(what As Variant, lookupRng As Range, defaultValue As Variant) As Variant
    Dim rv As Variant: rv = Application.VLookup(what, lookupRng, lookupRng.Columns.Count, False)
    If IsError(rv) Then
        VLookupVBA = defaultValue
    Else
        VLookupVBA = rv
    End If
End Function

Public Sub UsageExample()
    MsgBox VLookupVBA("ValueToFind", ThisWorkbook.Sheets("ReferenceSheet").Range("A:D"), "Not found!")
End Sub

答案 4 :(得分:0)

        Public Function VLOOKUP1(ByVal lookup_value As String, ByVal table_array As Range, ByVal col_index_num As Integer) As String
        Dim i As Long

        For i = 1 To table_array.Rows.Count
            If lookup_value = table_array.Cells(table_array.Row + i - 1, 1) Then
                VLOOKUP1 = table_array.Cells(table_array.Row + i - 1, col_index_num)
                Exit For
            End If
        Next i

        End Function

答案 5 :(得分:0)

Dim found As Integer
    found = 0

    Dim vTest As Variant

    vTest = Application.VLookup(TextBox1.Value, _
    Worksheets("Sheet3").Range("A2:A55"), 1, False)

If IsError(vTest) Then
    found = 0
    MsgBox ("Type Mismatch")
    TextBox1.SetFocus
    Cancel = True
    Exit Sub
Else

    TextBox2.Value = Application.VLookup(TextBox1.Value, _
    Worksheets("Sheet3").Range("A2:B55"), 2, False)
    found = 1
    End If