vlookup不在vba中工作但在excel中工作

时间:2017-08-12 18:35:49

标签: vba

我在单元格A2:B11的范围内有一些数据。我尝试做的是做一个vlookup来根据输入返回一个值,通过输入框。但是,Excel VBA编辑器不喜欢我的代码行与实际的VLOOKUP函数,但对我来说没有任何问题。请任何人都可以帮忙告诉我哪里出错了。这是代码.....

Sub getprice()

Dim PartNum As Variant
Dim Price As Double

Sheets("Sheet1").Activate
Set pricelist = Sheets("Sheet1").Range("A2:B11")
PartNum= InputBox("provide the part number")

Price = WorksheetFunction.VLookup(partnum, pricelist, 2, false)
MsgBox partnum & "costs" & price

End Sub

1 个答案:

答案 0 :(得分:0)

我已将InputBox替换为Application.InputBox,让您可以控制用户可以输入的数据类型,阅读更多相关信息,转到MSDN

另外,我添加了错误跟踪条件,以防Vlookup无法在PartNum范围内找到PriceList的mtach。

以下代码中的其他说明作为评论。

<强> 代码

Sub getprice()

Dim PartNum As Long
Dim Price As Double
Dim PriceList As Range

' set the Range object directly, there's no need to select the worksheet first
Set PriceList = Sheets("Sheet1").Range("A2:B11")

' use Application.InputBox with Type 1, ensures only numeric values are entered
PartNum = Application.InputBox(Prompt:="provide the part number", Type:=1)
' if the user pressed Cancel
If Len(PartNum) = 0 Then
    MsgBox "No Part Number entere", vbCritical
    Exit Sub
End If

' you need to trap a possible error in case Vlookup is unable to find a match in PriceList Range
If Not IsError(Application.VLookup(PartNum, PriceList, 2, False)) Then
    PartNum = Application.VLookup(PartNum, PriceList, 2, False)
    MsgBox PartNum & " costs " & Price
Else
    MsgBox PartNum & " not found in Range " & PriceList.Address
End If

End Sub