mySValue = InputBox("Enter the no. of rows to be considered")
Set myrange = Worksheets("UniqueSupNames").Range("A:B")
For counterSVar = 3 To mySValue
SupName = Range("A" & counterSVar)
SupId = Application.WorksheetFunction.VLookup(SupName, Range("myrange"), 2, False)
Range("K" & counterSVar).Value = SupId
Next counterSVar
以上是我的代码。请提出解决方案。 仅供参考-我创建了一个工作表,即“ UniqueSupNames”(在同一工作簿中),该工作表包含两列(A和B),分别包含供应商名称和供应商ID。
答案 0 :(得分:2)
使用Application.WorksheetFunction.VLookup
时,如果没有匹配项,则会出现中断错误。因此,如您遇到的那样,如果不处理该错误,则会得到错误Unable to get the VLookup property of the WorksheetFunction class
。但是,如果改用Application.VLookup
,则会出现不间断错误。另外,由于您已将查找范围分配给myrange
,因此Range("myrange")
应该替换为myrange
,正如@ARL已经提到的那样。因此,您应该具有以下条件...
SupID = Application.VLookup(SupName, myRange, 2, False)
此外,您可以使用IsError
...
Dim SupID As Variant
SupID = Application.VLookup(SupName, myRange, 2, False)
If IsError(SupID) Then
MsgBox "No match found!", vbExclamation
Else
MsgBox "SupID: " & SupID, vbInformation
End If
此外,如果您使用Application.InputBox
而不是InputBox
函数,则可以强制用户输入数字而不是文本等,并且可以测试用户是否已取消。例如...
Dim mySVAlue As Variant
'prompt the user to enter a number
mySVAlue = Application.InputBox(Prompt:="Enter the no. of rows to be considered", Type:=1)
'if user cancels, exit the sub
If mySVAlue = False Then Exit Sub
因此您的宏可以按如下方式重写...
'Force the explicit declaration of variables
Option Explicit
Sub LookupValues()
'declare the variables
Dim mySVAlue As Variant
Dim myRange As Range
Dim SupName As String
Dim SupID As Variant
Dim counterSVar As Long
'prompt the user to enter a number
mySVAlue = Application.InputBox(Prompt:="Enter the no. of rows to be considered", Type:=1)
'if user cancels, exit the sub
If mySVAlue = False Then Exit Sub
'set the range for the lookup table
Set myRange = Worksheets("UniqueSupNames").Range("A:B")
'lookup the values for the user selected rows
For counterSVar = 3 To mySVAlue
SupName = Range("A" & counterSVar).Value
SupID = Application.VLookup(SupName, myRange, 2, False)
Range("K" & counterSVar).Value = SupID
Next counterSVar
End Sub
答案 1 :(得分:1)
myrange已经是一个范围,因此range(“ myrange”)可能是您的问题所在。试试这个
For counterSVar = 3 To mySValue
SupName = Range("A" & counterSVar)
SupId = Application.WorksheetFunction.VLookup(SupName, myrange, 2, False)
Range("K" & counterSVar).Value = SupId
Next counterSVar