VBA vlookup数据不匹配

时间:2017-05-27 08:54:41

标签: excel vba excel-vba type-mismatch

我是VBA的新手,面临以下问题:

我需要返回IF公式返回的某个值,该公式基于数字数据保存在另一个工作表中。 我写过这样的东西,不过一直到运行IF部分,它给我的错误类型不匹配,问题似乎在vlookup找到的值中。我试图将它声明为长,变体等,但这没有帮助。但是,MsgBox正确地从另一张表中返回结果。另一张表格被格式化为数字。任何想法如何使它工作?

这是我现在的代码:

Option Explicit
Sub find()

Dim lookup As String
Dim pkgWidth, pkgLength, pkgHeight, displaySize, AllHeaders, headerweight, itemweight, classify  As Range
Dim lastrow As Variant
Dim cl As Range
Dim i As Integer
Dim widthh, lengthh, Heightt, display, Weight As Variant

'this part dynamically searches for the columns I need
Set AllHeaders = Worksheets("Sheet2").Range("1:1")
Set pkgWidth = AllHeaders.find("package_width")
Set pkgLength = AllHeaders.find("package_length")
Set pkgHeight = AllHeaders.find("package_height")
Set displaySize = AllHeaders.find("display_size")


Set headerweight = Worksheets("Sheet1").Range("1:1")
Set itemweight = headerweight.find("Item Weight")
Set classify = headerweight.find("AT")

lastrow = Cells(Rows.Count, 1).End(xlUp).Row

For i = 2 To lastrow

lookup = Worksheets("Sheet1").Cells(i, 1).Value
Set cl = Worksheets("Sheet1").Cells(i, classify.Column)

'here the values are being looked up from another sheet
widthh = Application.VLookup(lookup, _
Worksheets("Sheet2").Range("A1").CurrentRegion, pkgWidth.Column, False)

lengthh = Application.VLookup(lookup, _
Worksheets("Sheet2").Range("A1").CurrentRegion, pkgLength.Column, False)

Heightt = Application.VLookup(lookup, _
Worksheets("Sheet2").Range("A1").CurrentRegion, pkgHeight.Column, False)

display = Application.VLookup(lookup, _
Worksheets("Sheet2").Range("A1").CurrentRegion, displaySize.Column, False)

Weight = Application.VLookup(lookup, _
Worksheets("Sheet1").Range("A1").CurrentRegion, itemweight.Column, False)

If display > 6 Then
    If Weight < 25 Then
        cl.Value = 1.01
        Else
        cl.Value = 1.02
        End If
    Else
        If widthh >= 1970 Or lengthh >= 1970 Or Heightt >= 1970 Then
            If Weight <= 8 Then
            cl.Value = 3.01
            Else
                If Weight >= 35 Then
                cl.Value = 3.02
                Else
                cl.Value = 3.03
                End If
            End If
         Else
            If Weight <= 3 Then
            cl.Value = 5.01
            Else
                If Weight >= 8 Then
                cl.Value = 5.03
                Else
                cl.Value = 5.02
                End If
        End If
    End If
End If

Next i

End Sub

1 个答案:

答案 0 :(得分:2)

使用Application.VLookup(或其任何变体)时,您必须考虑到它可以返回#N/A,如documentation中所述:

  

如果lookup_value小于table_array第一列中的最小值,VLOOKUP将返回#N / A错误值。

如果例如display获得该值,那么表达式display > 6将为您提供类型不匹配错误。

为了防止这种情况发生,请更改代码的逻辑,以便VLookup保证不返回#N/A(如果在您的情况下这是可能的,我不能说),或者为此测试错误值,如下所示:

If IsError(display) Then
    ' Treat the error condition...
ElseIf display > Then
    ' ...etc.

获得VLookup电话结果的其他变量可能需要采取相同的预防措施。