使用VLookup从工作表中插入特定数据

时间:2016-01-28 20:31:03

标签: excel vba excel-vba

有人可以帮助我吗 - 我有一个工作表,并且在输入代码时我需要它从该行中拉出某些设置单元并将其显示在活动工作表上。 就我而言,这可能会让我知道我对VBA的态度是多么无知,而且它不起作用。

Sub AddProduct()
On Error GoTo MyErrorHandler:
Dim Code As Long
Code = B4
Sheets("Code Input Sheet").Range(A9) = Application.VLookup(Code,Worksheets("Cost Sheet").Range("A2:XFD1048576"), 1, False)
ActiveCell.End(xlRight).Offset(0, 1).Select
Selection = Application.VLookup(Code, Worksheets("Cost Sheet").Range("A2:XFD1048576"), 2, False)
ActiveCell.End(xlRight).Offset(0, 1).Select
Selection = Application.VLookup(Code, Worksheets("Cost Sheet").Range("A2:XFD1048576"), 5, False)
ActiveCell.End(xlDown).Offset(1, 0).Select
MyErrorHandler:
If Err.Number = 1004 Then
MsgBox "Code doesn't exist."
End If
End Sub

希望这是有道理的 感谢

修改

Screenshot

我可能需要从头开始,但基本上我需要的是:用户在B4中输入代码,通过按钮运行宏,如果它存在则在第二张表上查找,并拉动从第一张纸上的代码行到A9:C9的三个单元格。然后希望可以重复该过程,数据将转到下面的下一行。希望这不是一个太多的问题!

1 个答案:

答案 0 :(得分:1)

使用Range.Find method

而不是VLOOKUP
Sub AddProduct()
Dim code As Variant
Dim c As Range
Dim ws As Worksheet
Dim lastrow As Long

Set ws = ActiveSheet

code = ws.Range("B4")

'Find code and set c to the cell    
Set c = Worksheets("Cost Sheet").Range("A:A").Find(code)

If c is Nothing Then
    'if the code is not found
    MsgBox "Not Found"
    Exit Sub
Else
    'this finds the next empty row
    lastrow = ws.Range("A" & ws.Rows.Count).End(xlUp).Row + 1
    ws.Range("A" & lastrow) = c
    ws.Range("B" & lastrow) = c.Offset(, 1)
    ws.Range("C" & lastrow) = c.Offset(, 4)
End If


End Sub