VBA Vlookup返回错误的结果

时间:2016-05-14 17:48:38

标签: excel vba vlookup

我目前正在尝试创建一个应用程序,我可以在使用VBA时将销售存储在单个工作表中。

当我尝试使用Vlookup确定ProductID的价格以便我不必自己输入值时,Vlookup将返回相同的值" 2015"

我不知道它出了什么问题

这是工作表的布局:Layout 这是我的Userform的布局:Layout

这是我在命令按钮上使用的代码:

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

有人可以帮我解决问题吗?它可能只是我目前忽略的一件小事。

谢谢, 马亭

2 个答案:

答案 0 :(得分:3)

您的代码有2个问题; “J2:L2000”应替换为Range(“J2:L2000”)(2015年是2015年错误的整数版本)

如果Vlookup找不到Textbox3.Value,您的代码将无效:在这种情况下,它将返回错误:代码看起来应该更像

{{1}}

答案 1 :(得分:1)

您的代码引发了“2015错误”,因为您将CREATE TABLE IF NOT EXISTS player_data ( UniqueID string, Money int ) 置于 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 转换Price变量的需要。希望其他人可以清楚地说明为什么CInt中的TextBox3.Value会引发错误?

相关问题