根据另一个单元格中的值搜索和查找值

时间:2014-01-15 23:36:09

标签: excel vba

我正在尝试构建一个搜索特定列的宏。

以下是步骤:
1.用户在单元格中输入一个数字,然后执行宏 2.根据用户输入的值,宏将在列中找到文本。

除了我不知道如何定义用户输入的单元格的值之外,我还能很好地工作。这里的任何帮助将不胜感激。

Sheets("New Version ").Select
    Range("B4").Select
    Sheets("PN_List").Select
    Columns("I:I").Select
    'below is where I struggle
    Selection.Find(What:=(""), After:=ActiveCell, LookIn:=xlFormulas, _
        LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
        MatchCase:=False, SearchFormat:=False).Activate 

2 个答案:

答案 0 :(得分:0)

假设用户在单元格B4中输入一个数字,那么您只需将代码调整为:

Selection.Find(What:=Range("B4").Value, After:=ActiveCell, LookIn:=xlFormulas, _
    LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
    MatchCase:=False, SearchFormat:=False).Activate 

答案 1 :(得分:0)

您可以通过两种方式完成此操作。

<强>数字1:

基于模块:(模块中的代码)

Sub Sample()

Dim search_range as Range, search_value as Range, _
    lastcell as Range, foundcell as Range
Dim ws as Worksheet

Set ws = Thisworkbook.Sheets("PN_List")
Set search_range = ws.Range("I1", ws.Range("I" & Rows.Count).End(xlUp))
Set lastcell = search_range.Cells(search_range.Cells.Count)
Set search_value = Thisworkbook.Sheets("New Version").Range("B4")

Set foundcell = search_range.Find(What:=search_value, After:=lastcell, LookIn:=xlFormulas, _
    LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
    MatchCase:=False, SearchFormat:=False).Activate

If Not foundcell Is Nothing Then foundcell.Activate Else Msgbox "Not Found"

End Sub

<强> NUMBER2:

基于工作表事件。 (表格中的代码)

Private Sub Worksheet_Change(ByVal Target as Range)

Dim search_range as Range, search_value as Range, _
    lastcell as Range, foundcell as Range
Dim ws as Worksheet

Set ws = Thisworkbook.Sheets("PN_List")
Set search_range = ws.Range("I1", ws.Range("I" & Rows.Count).End(xlUp))
Set lastcell = search_range.Cells(search_range.Cells.Count)
Set search_value = Thisworkbook.Sheets("New Version").Range("B4")

If Not Intersect(Target, search_value) Is Nothing Then
query = Msgbox("Search data?", vbYesNo)
If query = 7 Then Exit Sub
Set foundcell = search_range.Find(What:=search_value, After:=lastcell, LookIn:=xlFormulas, _
    LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
    MatchCase:=False, SearchFormat:=False).Activate

If Not foundcell Is Nothing Then foundcell.Activate Else Msgbox "Not Found"

End Sub

您在B4中输入数据的第一个然后运行宏 每次更改B4中的值时,第二个都会触发 将出现一个msgbox,询问您是否要搜索输入的数据。

希望这有帮助。