首页 > 解决方案 > 如何将 HLookup 结果与“”进行比较?

问题描述

我尝试使用 Hlookup。

代码返回以下错误:

“无法获取 WorksheetFunction 类的 HLookup 属性”</p>

我尝试了错误处理,但我得到:

运行时错误“13”类型不匹配。

我意识到这是因为数据类型冲突。我如何If myHLookupResult <> "" Then MsgBox myHLookupResult以一种可以处理长数据类型的方式表达。

Dim myHLookupResult As Long

On Error Resume Next
myHLookupResult = WorksheetFunction.HLookup(CalcSheet.Range("C81"), CalcSheet, 57)
On Error GoTo 0
                        
If myHLookupResult <> "" Then MsgBox myHLookupResult
                        
pmp.Offset(0, 14).Value = myHLookupResult

标签: excelvba

解决方案


说明@BigBen 的评论,并查看您的代码:

  • 使用变体类型,以便您可以处理返回的错误
  • 使用变量设置查找变量和范围(非必需)
  • 定义是否要与查找函数中的最后一个参数完全匹配

旁注:您的查找范围设置为工作表的名称(或至少出现)

阅读代码的注释并根据您的需要进行调整。

Public Sub HLookupResult()
    
    ' Not required, but nice to set the value to a variable
    Dim lookupValue As Variant
    lookupValue = CalcSheet.Range("C81").Value
    
    ' Not required, but nice to set the lookup range to a variable
    Dim lookupRange As Range
    Set lookupRange = CalcSheet.Range("A1:B5")
    
    ' Use variant so if not found can handle the error
    Dim resultValue As Variant
    resultValue = Application.HLookup(lookupValue, lookupRange, 2, False)
    
    ' Check the error and do something
    If IsError(resultValue) Then
        MsgBox "Not found"
    Else
        MsgBox resultValue
    End If

End Sub

推荐阅读