2016-06-13 25 views
1

我想從列中返回多個匹配到組合框。所以,如果我有這樣的命名一列「變量:和搜索‘變量1’將近似的多個匹配返回給組合框

enter image description here

然後我想在ComboBox這樣的輸出。如果沒有發現匹配,那麼‘不匹配’。 enter image description here

+0

如果你在A列有'zVariable' - 應該出現在ComboBox? –

+0

也是組合框的窗體或ActiveX控件?它是在工作表上還是在用戶窗體上? –

+0

@Robin - 它在用戶窗體上。只有近似匹配出現在組合框中,無論我們在文本框中搜索什麼。 – user2458552

回答

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

+0

非常感謝!就像一個魅力..至於找不到匹配,可能我可以計數的CombBox值,將返回一個不匹配,如果計數爲0 .. – user2458552

+0

@ user2458552 - 我更新了'不匹配'位的示例代碼 - 猜你可以使用ComboBox中的項目數 - 但我只是創建了一個單獨的計數器。相同的區別:) –

+0

非常感謝!那完美的作品 – user2458552