2013-02-23 102 views
1

我的VLookup函數有問題,因爲它沒有找到我知道的範圍內的值。產品變量必須保持字符串,因爲我正在查找數字和帶有文本的混合數字。另外我的教練不允許使用變體。VLookup的VBA問題

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

+0

你肯定值不包含額外的空間或類似這樣的東西嗎? Excel中的vlookup是否返回正確的結果? – 2013-02-23 22:24:34

+0

是的,我確定這兩個值是相同的。查詢的值也是一般格式。 – shadowjfaith 2013-02-23 22:35:16

+0

'Application.VLookup(Val(Product),myRange,3,False)'試一試,只是爲了確保 – 2013-02-23 22:50:28

回答

2

您檢查的數據是類型編號,但是,您爲VLOOKUP函數提供了一個字符串。

因此,與其Application.VLookup(Product, myRange, 3, False),使用

Application.VLookup(Val(Product), myRange, 3, False) 
+0

這適用於數字值;然而,當我輸入另一個值如「45-C-33」時,它沒有找到。 – shadowjfaith 2013-02-23 23:02:39

+2

我已經實施了Val(產品)和產品之間的isnumeric。感謝你的回答。 – shadowjfaith 2013-02-23 23:08:03