在单元格范围内搜索在用户窗体的文本框中输入的字符串并返回行的列值

问题描述 投票:0回答:1

我的 A、B、C、D 列中有数据。我有一个用户窗体,我将在其中输入要在文本框中搜索的字符串。

当我单击用户窗体上的搜索按钮时,它应该在 A、B 和 C 列中搜索输入的字符串。无论在哪一行找到该字符串,它都应该在列表框中显示该行的 D 列值。

示例:
enter image description here

从上面的示例中,当我搜索字符串“Bag”时,我的列表框应具有以下值:return1、return2、return3

Private Sub CommandButton3_Click()
    row_num = 1
    Application.ScreenUpdating = False
    searchString = srchtxt.value
    Me.ListBox2.Clear
    If srchtxt.value Like "*[!.A-Za-z_ ]*" Or (IsNumeric(srchtxt.value) = True) Then
        Exit Sub
    Else
        Do
            DoEvents
            row_num = row_num + 1
            item_num = SHEET17.Range("A" & row_num)
            item_num1 = SHEET17.Range("B" & row_num)
            item_num2 = SHEET17.Range("C" & row_num)
            item_desc = SHEET17.Range("D" & row_num)
            If InStr(1, item_num, searchString, vbTextCompare) > 0 Then
                Me.ListBox2.AddItem (item_desc)
            ElseIf InStr(1, item_num1, searchString, vbTextCompare) > 0 Then
                Me.ListBox2.AddItem (item_desc)
            ElseIf InStr(1, item_num2, searchString, vbTextCompare) > 0 Then
                Me.ListBox2.AddItem (item_desc)
            End If
        Loop Until row_num = 10000
    End If
End Sub
excel vba string search
1个回答
2
投票

使用查找和查找下一个

更新 - 已排序的唯一值

Option Explicit

Private Sub CommandButton3_Click()

    Dim sSearch As String, sAddr As String
    Dim rngFound As Range, rngSearch As Range
   
    Dim arList As Object, i As Long, colD As String
    Set arList = CreateObject("System.Collections.ArrayList")
    
    ' check user entry
    sSearch = Trim(srchTxt.Value)
    If Len(sSearch) = 0 Then
        MsgBox "No search text entered", vbCritical
        Exit Sub
    End If
    
    ' column A and C
    With Sheet17
         Set rngSearch = Intersect(.UsedRange, .Columns("A:C")).Offset(1) ' exclude header
    End With
    
    ' search for text and fill arraylist with unique col D value
    Me.ListBox2.Clear
    
    Set rngFound = rngSearch.Find(sSearch, _
           LookIn:=xlValues, lookat:=xlPart, MatchCase:=False)
        
    If Not rngFound Is Nothing Then
        sAddr = rngFound.Address
        Do
            colD = Trim(rngFound.Offset(0, 4 - rngFound.Column)) ' Col D
            If Not arList.contains(colD) Then arList.Add colD
            Set rngFound = rngSearch.FindNext(rngFound)
        Loop While rngFound.Address <> sAddr
    End If
    
    
    ' update listbox with sorted values
    arList.Sort
    For i = 1 To arList.Count
       ListBox2.AddItem arList(i - 1)
    Next
    
End Sub
© www.soinside.com 2019 - 2024. All rights reserved.