使用宏将搜索框实现到当前工作表中

时间:2014-01-14 09:50:22

标签: excel vba

我的宏目前的工作方式是按CTRL + F打开搜索框,搜索REF1或REF2。如果找到信息,它会复制到下一个单元格,以显示它在那里。如果找不到该信息,它会粘贴在单元格L4中搜索的数据,以便打印标签。

我正在尝试做什么:

删除CTRL + F并基本上从一个单元格运行(比如说单元格L18)。但是,扫描时,扫描仪基本上输入数字,然后按回车键。

我在想,是否有可能让它像这样运行。

选择单元格L18,然后继续扫描,直到: A)完成清单 - 没有遗漏任何事项 B)如果REF1 / REF2不匹配,将该数据粘贴到单元格L4中以便打印标签。

(使用CTRL + F的当前版本):http://oi39.tinypic.com/mima9x.jpg

(我需要的例子):http://oi42.tinypic.com/24fiwt1.jpg

当前的宏:

    Sub Extra_Missing_Item()   Application.ScreenUpdating = False
   Dim rangeToSearch As Range
   With Sheets(1)
      Set rangeToSearch = .Range("A2:B" & .Range("A" & .Rows.Count).End(xlUp).Row)
   End With


   Dim searchAmount As String
   searchAmount = InputBox("Scan the REF1 or REF2:")


   Dim cell As Range


   Set cell = rangeToSearch.Find(searchAmount, LookIn:=xlValues)
   With Sheets(1)
      If Not cell Is Nothing Then
        .Range("E" & cell.Row & ":G" & cell.Row).Value = _
           .Range("A" & cell.Row & ":C" & cell.Row).Value
      Else
MsgBox "REF1/REF2: " & searchAmount & " shouldn't be here"
        .Range("L4").Value = searchAmount
            Range("L9").Select
      End If
   End With


   Application.ScreenUpdating = True
End Sub

1 个答案:

答案 0 :(得分:1)

我想我明白你需要什么。每当表单上的任何单元格发生更改时,此宏都会调用(但如果更改的单元格不是L18,则宏不执行任何操作):

Private Sub Worksheet_Change(ByVal Target As Range)

    If Application.Intersect(Target, Range("L18")) Is Nothing Then
        Exit Sub
    End If


    Dim rangeToSearch As Range
    Dim searchAmount As String
    Dim cell As Range

    Application.ScreenUpdating = False
    Application.EnableEvents = False

    Set rangeToSearch = Range("A2:B" & Range("A" & Rows.Count).End(xlUp).Row)

    searchAmount = Target.value

    Set cell = rangeToSearch.Find(searchAmount, LookIn:=xlValues)
    If Not cell Is Nothing Then
        Range("E" & cell.Row & ":G" & cell.Row).value = _
        Range("A" & cell.Row & ":C" & cell.Row).value
    Else
        MsgBox "REF1/REF2: " & searchAmount & " shouldn't be here"
        Range("L4").value = searchAmount
    End If

    Range("L18").Select

    Application.EnableEvents = True
    Application.ScreenUpdating = True
End Sub

将此宏放在工作表模块中(与数据所在的工作表对应):

enter image description here