VBA查找数据不匹配

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

我需要返回IF公式返回的某个值,基于数字数据,保存在另一个工作表中。 我已经写了类似这样的东西,但是一直到运行IF部分的时候,它给了我错误types不匹配 ,并且问题似乎在由vlookupfind的值中。 我试图宣布它很长,变体等,但没有帮助。 但是,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 

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

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

如果例如display获得该值,那么expression式display > 6会给你types不匹配的错误。

所以为了防止这种情况,要么改变你的代码的逻辑,以保证VLookup不会返回VLookup #N/A (如果这是可能的话,我不能说),或者testing这个错误值,像这样:

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

对于获得VLookup调用结果的其他variables,可能需要采取相同的预防措施。