2016-05-14 187 views
0

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

当我尝试使用VLOOKUP确定的ProductID的价格,使我没有在自己输入的值VLOOKUP总是返回相同的值“2015”

我不知道到哪里去错误

这是表的布局:Layout 这是我的用户窗体的布局: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

尝试用Productprijs = CInt(Range(“L”&Application.Match(TextBox3.Value))替换'Productprijs = CInt(Application.VLookup(TextBox3.Value,“J2:L2000”,3,False))' ,Range(“J:J”),0)))' –

回答

3

有2个问题,你的代码; “J2:L2000”应该用范围(“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 
1

您的代码抛出“2015年错误”,因为你把TextBox3.ValueVLookup函数作为第一个参数。请注意以下代码的工作原理:

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变量的需要。希望别人能说清楚为什么VLookup内的TextBox3.Value会引发错误?