[英]VBA Vlookup returns wrong results
我目前正在嘗試制作一個應用程序,以便在使用VBA時可以將銷售存儲在單個工作表中。
當我嘗試使用Vlookup確定ProductID的價格時,不必自己輸入值,Vlookup總是返回相同的值“ 2015”
我不知道哪里出了問題
這是我在命令按鈕上使用的代碼:
Private Sub CommandButton1_Click()
Dim emptyRow As Long
Dim r As Range
Dim Productprijs As Integer
Dim productaantal As Integer
Dim Eindprijs As Integer
Sheet1.Activate
emptyRow = WorksheetFunction.CountA(Range("A:A")) + 1
Cells(emptyRow, 1).Value = TextBox1.Value
Cells(emptyRow, 2).Value = TextBox2.Value
Cells(emptyRow, 3).Value = TextBox3.Value
Cells(emptyRow, 5).Value = TextBox4.Value
Productprijs = CInt(Application.VLookup(TextBox3.Value, "J2:L2000", 3, False))
productaantal = TextBox2.Value
Eindprijs = Productprijs * productaantal
Cells(emptyRow, 4).Value = Eindprijs
UserForm1.Hide
有人可以幫我解決我的問題嗎? 這可能只是我目前忽略的小事。
謝謝,馬丁(Martijn)
您的代碼有2個問題; “ J2:L2000”應替換為Range(“ J2:L2000”)(2015是2015錯誤的整數版本)
如果Vlookup找不到Textbox3.Value,則您的代碼將無法正常工作:在這種情況下,它將返回錯誤:代碼應更像這樣
Sub testv()
Dim v As Variant
Dim i As Long
v = Application.VLookup(9, Range("A1:a3"), 1, False)
If Not IsError(v) Then
i = CLng(v)
Else
MsgBox "not Found"
End If
End Sub
您的代碼拋出“ 2015錯誤”,因為您將TextBox3.Value
放在 VLookup
函數中作為第一個參數。 請注意,以下代碼有效:
Private Sub CommandButton1_Click()
Dim emptyRow As Long
Dim Price As Variant
Dim Quantity As Double
Dim Total As Double
Dim x As Double
'This finds the next empty row in the first table
emptyRow = WorksheetFunction.CountA(Range("A:A")) + 1
'Place the new values from the UserForm to the table
Cells(emptyRow, 1).Value = TextBox1.Value 'Date
Cells(emptyRow, 2).Value = TextBox2.Value 'Quantity
Cells(emptyRow, 3).Value = TextBox3.Value 'ProductID
Cells(emptyRow, 5).Value = TextBox4.Value 'Customer
'Assign the value of the ProductID text box to x
x = TextBox3.Value
'Calculate the total price, using x instead of TextBox3.Value
Price = Application.VLookup(x, Range("J2:L3"), 3, False)
Quantity = TextBox2.Value
Total = Price * Quantity
Cells(emptyRow, 4).Value = Total
UserForm1.Hide
End Sub
這也消除了使用CInt
轉換Price變量的需要。 希望別人能清楚地說明為什么在TextBox3.Value
里面VLookup
拋出一個錯誤?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.