我是vba编程的新手。任何人都可以帮我解决这个问题:
Sub GetPrice()
Dim PartNum As Variant
Dim Price As Variant
PartNum = InputBox("Enter the Part Number")
Sheets("Sheet2").Activate
Price = WorksheetFunction._
VLookup(PartNum, Range("A2:C20"), 2, False)
MsgBox PartNum & "costs" & Price
End Sub
每次我尝试运行此代码时,输入框都没问题,但随后出现错误:无法获取VLookup属性...在我之后
任何帮助表示感谢。
答案 0 :(得分:0)
如果您的查找表中没有查找值,则会出现一些模棱两可的错误。尝试将其包装在一些错误纠正中以查看它是否有帮助:
Sub GetPrice()
Dim PartNum As Variant
Dim Price As Variant
PartNum = InputBox("Enter the Part Number")
Sheets("Sheet2").Activate
On Error GoTo out
Price = WorksheetFunction.VLookup(PartNum, Sheet2.Range("A2:C20"), 2, False)
MsgBox PartNum & "costs" & Price
Exit Sub
out:
MsgBox "Part not found"
End Sub
答案 1 :(得分:0)
Sub GetPrice()
Dim PartNum As Variant
Dim Price As Variant
PartNum = InputBox("Enter the Part Number")
Price = Application.VLookup(PartNum, Sheets("Sheet2").Range("A2:C20"), 2, False)
If Not IsError(Price) Then
MsgBox PartNum & " costs " & Price
Else
MsgBox "Part Number '" & PartNum & "' was not found!"
End If
End Sub
答案 2 :(得分:0)
我个人总是在Excel宏中使用Cells([rowIndex],[columnIndex])。这是与数据交互所需的最基本(也是大部分时间唯一)功能。如果你试图只获得价值而不是邮件,那么VLookUp是好的。使用Cells()可以获得更多的力量。
这是一种在工作表的已定义部分中搜索特定字符串的实现:
Sub searchPartNumber()
Dim ret() As Integer
'initialize the cell space to search in.
Dim fromCell(1) As Integer
Dim toCell(1) As Integer
'index 0: row
'index 1: column
'(A,2):(C,20) looks like this:
fromCell(0) = 1
fromCell(1) = 2
toCell(0) = 3
toCell(1) = 20
PartNum = InputBox("Enter the Part Number")
ret = searchTable(PartNum, fromCell, toCell)
If ret(0) = 1 Then
MsgBox ("The value searched is in Cell " & ret(1) & ", " & ret(2) & " and the value searched for is " & Cells(ret(1), 2))
Else
MsgBox "This part number could not be found."
End If
End Sub
Function searchTable(ByVal searchValue As String, ByRef fromCell() As Integer, ByRef toCell() As Integer) As Integer()
Dim ret(2) As Integer
'index 0: 1 = found, 0 = not found
'index 1/2: row and column of found element
ret(0) = 0
Dim i As Integer, j As Integer
For i = fromCell(0) To toCell(0)
For j = fromCell(1) To toCell(1)
If (CStr(Cells(i, j)) = searchValue) Then
'Item found
ret(0) = 1
ret(1) = i
ret(2) = j
searchTable = ret
Exit Function
End If
Next
Next
End Function
答案 3 :(得分:0)
谢谢大家!
我想我发现了问题所在。我不能将“PartNum”定义为Variant(我仍然没有得到它?我认为Variant可以替换任何潜在类型的数据)。
在我将“PartNum”定义为Integer或Double之后,我可以非常好地运行此vlookup函数,因为我尝试查找的值实际上是数字!