vlookup不在vba中工作,但在excel中工作
我在单元格A2:B11中有一些数据。我要做的是,通过输入框,根据输入返回一个值。然而,excelvba编辑器不喜欢我的代码中带有实际VLOOKUP函数的那一行,但对我来说,它没有任何问题。请任何人帮帮忙,告诉我哪里出了问题。这是代码vlookup不在vba中工作,但在excel中工作,vba,Vba,我在单元格A2:B11中有一些数据。我要做的是,通过输入框,根据输入返回一个值。然而,excelvba编辑器不喜欢我的代码中带有实际VLOOKUP函数的那一行,但对我来说,它没有任何问题。请任何人帮帮忙,告诉我哪里出了问题。这是代码 Sub getprice() Dim PartNum As Variant Dim Price As Double Sheets("Sheet1").Activate Set pricelist = Sheets("Sheet1").Range("A2:B11"
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
我已将您的
输入框
替换为应用程序。输入框
,用于控制用户可以输入的数据类型。要了解更多信息,请转到
此外,我还添加了一个错误跟踪标准,以防Vlookup
无法在PriceList
范围中找到PartNum
的mtach
下面代码中的其他解释作为注释
代码
我已将您的
输入框
替换为应用程序。输入框
,用于控制用户可以输入的数据类型。要了解更多信息,请转到
此外,我还添加了一个错误跟踪标准,以防Vlookup
无法在PriceList
范围中找到PartNum
的mtach
下面代码中的其他解释作为注释
代码
你的代码对我有用。我怀疑问题出在您使用的特定数据中-示例
PartNum
会是什么样子?(例如,它是类似于ABC-123-AS
还是仅仅是1234
?)InputBox将返回一个字符串,如果partNum是价目表中的一个数字,它将找不到匹配项。您需要将其更改为数字。VBA编辑器不喜欢该行的意思是什么?仅供参考:绝对没有理由在代码表(“Sheet1”)中使用该行。激活您的代码对我有效。我怀疑问题出在您使用的特定数据中-示例PartNum
会是什么样子?(例如,它是类似于ABC-123-AS
还是仅仅是1234
?)InputBox将返回一个字符串,如果partNum是价目表中的一个数字,它将找不到匹配项。您需要将其更改为数字。VBA编辑器不喜欢该行的意思是什么?仅供参考:绝对没有理由在代码表(“Sheet1”)中使用该行。激活
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