【发布时间】:2013-02-23 22:20:16
【问题描述】:
我的 VLookup 函数有问题,因为它没有找到我知道在该范围内的值。 Product 变量必须保留为字符串,因为我正在查找数字和混合数字与文本。我的导师也不允许使用变体。
Sub LookupValue()
Dim Product As String
Dim ErrCheck As Boolean
Dim Quantity As Integer
Dim Discount As Double
Dim myRange As Range
Set myRange = Worksheets("Prices").Range("A2:C21")
ErrCheck = True
'Obtaining VLookup Value
Product = InputBox("Enter the product's code.")
'Error checking
Do Until ErrCheck = False
If Product = "" Then
ErrCheck = True
MsgBox ("Not a valid entry.")
Product = InputBox("Enter the product's code.")
ElseIf IsError(Application.VLookup(Product, myRange, 3, False)) Then
ErrCheck = True
MsgBox ("The value entered was not found.")
Product = InputBox("Enter the product's code.")
Else
ErrCheck = False
End If
Loop
'Obtaining Quantity Value
Quantity = InputBox("Enter the quantity ordered.")
'Error checking
Do Until ErrCheck = False
If IsNumeric(Quantity) = False Then
ErrCheck = True
MsgBox ("Not a valid entry.")
Quantity = InputBox("Enter the quantity ordered.")
Else
ErrCheck = False
End If
Loop
'Obtaining discount rate
If Quantity < 25 Then
Discount = 0.1
If Quantity < 50 Then
Discount = 0.15
If Quantity < 75 Then
Discount = 0.2
If Quantity < 100 Then
Discount = 0.25
If Quantity >= 100 Then
Discount = 0.3
End If
End If
End If
End If
End If
'Filling in cells
Sales.Range("B2") = Product
Sales.Range("B3") = Application.VLookup(Product, myRange, 2, False)
Sales.Range("B4") = Quantity
Sales.Range("B5") = Discount
Sales.Range("B6") = Application.VLookup(Product, myRange, 3, False)
Sales.Range("B7") = Range("B6").Value * Quantity
Sales.Range("B8") = Range("B7").Value * Discount
Sales.Range("B9") = Application.WorksheetFunction.Sum("B7:B8")
End Sub
查找范围的一个例子是
89044 |小部件 | 12:00
【问题讨论】:
-
您确定该值不包含额外的空格或类似的东西吗? Excel 中的 vlookup 是否返回正确的结果?
-
是的,我确信这两个值是相同的。正在查找的值也是通用格式。
-
试试
Application.VLookup(Val(Product), myRange, 3, False),只是为了确定 -
这成功了!我以为我试过了,但显然我改变了其他东西,没有再试一次。感谢您的帮助。