返回与ComboBox的近似多个匹配项

时间:2016-06-13 06:56:31

标签: excel vba excel-vba combobox macros

我想从列返回多个匹配项到ComboBox。所以,如果我有一个名为“变量:”的列,并搜索“variable1”

enter image description here

然后我想在ComboBox中输出这样的输出。如果没有匹配,那么“不匹配”。enter image description here

1 个答案:

答案 0 :(得分:2)

我将使用“近似匹配”的假设。是a)不区分大小写,并且b)只需要将搜索字符串放在Range值内的某个位置。在UserForm

中试用此代码
Option Explicit

Private Sub CommandButton1_Click()

    Dim rngSource As Range
    Dim rngCell As Range
    Dim strValueToApproximatelyMatch As String
    Dim lngCounter As Long
    Dim lngResultCount As Long

    'get candidate values and put to an array
    Set rngSource = Sheet1.Range("A2:A10")

    'get value to match approximately
    strValueToApproximatelyMatch = Me.TextBox1.Value

    'clear combo box
    Me.ComboBox1.Clear

    'set result count to 0
    lngResultCount = 0

    'iterate array and look for approximate match to input
    For lngCounter = 1 To rngSource.Rows.Count
        'get candidate
        Set rngCell = rngSource.Cells(lngCounter, 1)
        'test candidate against value to approximately match
        If InStr(1, rngCell.Value, strValueToApproximatelyMatch, vbTextCompare) > 0 Then
            'add to list if test passed
            Me.ComboBox1.AddItem rngCell.Value
            'increment result count
            lngResultCount = lngResultCount + 1
        End If
    Next lngCounter

    'add the no match if result count =0
    If lngResultCount = 0 Then
        Me.ComboBox1.AddItem "No Match"
    End If

End Sub

这是我得到的输出:

enter image description here