【发布时间】:2017-10-28 03:12:12
【问题描述】:
我是 VBA 新手,面临以下问题:
我需要返回某个值,由 IF 公式返回,基于数字数据,保存在另一个工作表中。 我写过这样的东西,但是在运行 IF 部分时,它总是给我错误 Type mismatch,问题似乎出在 vlookup 发现的值中.我试图将它声明为 long、variant 等等,但这并没有帮助。但是,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
【问题讨论】:
-
(a) 插入
Option Explicit作为代码的第一行,并确保显式声明所有变量。 (b) 在使用变量weightcol之前为其赋值。 (c) 使用变量weight而不是weigth(d) 你是否故意使用Application.Lookup而不是Application.VLookup? -
如果,在您将代码修复为有效后,它仍然给出类型不匹配错误,请告诉我们错误发生在哪一行,以及该行使用的所有变量的值是什么。
-
在遇到错误之前单步执行代码时 display 和 wieght 的值是多少?
-
我的工作表中似乎有一个错误,其中一个隐藏行无法取消隐藏并且无法读取哪些值。 (我不知道为什么),所以在接下来的错误恢复中,整个东西都起作用了。非常感谢,至少我发现代码可以正常工作了。
-
请注意,您最新版本的代码将
pkgWidth、pkgLength、pkgHeight、displaySize、AllHeaders、headerweight和itemweight声明为Variant, 并且只有classify作为Range
标签: vba excel type-mismatch