在VBA中使用VLOOKUP()

时间:2017-09-03 16:29:08

标签: excel excel-vba excel-formula vba

我们在工作表中有一个简短的表格,如:

enter image description here

A1 A3 的值是这些公式的结果:

=DATE(1999,12,15)
=DATE(1945,1,18)
=DATE(2020,2,23)

如果我尝试在工作表单元格中使用 VLOOKUP()

=VLOOKUP(DATE(1945,1,18),A1:B3,2)

我得到了正确的结果(Moe)

enter image description here

但是在VBA中:

Sub RetrieveName()
    Dim d As Date, nam As String, rng As Range
    d = DateSerial(1945, 1, 18)
    Set rng = Range("A1:B3")
    nam = Application.WorksheetFunction.VLookup(d, rng, 2)
    MsgBox nam
End Sub

我收到错误:

enter image description here

我们目前的解决方法是使用:

Sub RetrieveName2()
    Dim d As Long, nam As String, rng As Range
    d = 16455
    Set rng = Range("A1:B3")
    nam = Application.WorksheetFunction.VLookup(d, rng, 2)
    MsgBox nam
End Sub

对于我的生活,我看不出原始代码有什么问题?

1 个答案:

答案 0 :(得分:2)

Scott Craner是正确的,在将VBA日期传递给VLOOKUP之前将其转换为Double可以正常工作 我认为问题是Excel和VBA正在使用Range.Value规则将值传递回VLOOKUP函数。 Excel没有真正的日期数据类型 - Excel中的日期是带有日期格式的双精度数。 Range.Value尝试将格式化为日期的Excel数字转换为VBA日期,反之亦然,将VBA日期传递回Excel,但VLOOKUP不理解伴随格式代码的数字。

Sub RetrieveName()
    Dim d As Double, nam As Variant, rng As Range
    d = DateSerial(1945, 1, 18)
    Set rng = Range("A1:B3")
    nam = Application.WorksheetFunction.VLookup(d, rng, 2)
    MsgBox nam
End Sub

Sub RetrieveName2()
    Dim d As Variant, nam As Variant, rng As Range
    '
    ' note Range("a2").value will fail
    '
    d = Range("a2").Value2
    Set rng = Range("A1:B3")
    nam = Application.WorksheetFunction.VLookup(d, rng, 2)
    MsgBox nam
End Sub