简体   繁体   English

如何在Excel VBA中使用ComboBox值作为条件自动过滤列

[英]How to Auto Filter a column using ComboBox value as Criteria in Excel VBA

I have a spreadsheet that contains a list of Phone brands and Phone models (Phone brands are in column A, and Phone models are in column B) 我有一个电子表格,其中包含电话品牌和电话型号的列表(电话品牌在A列中,而电话型号在B列中)

I'm trying to do an ActiveX program that allows Users to select a Phone brand from ComboBox1 and Filter column A using the Value of the ComboBox1. 我正在尝试做一个ActiveX程序,该程序允许用户从ComboBox1和Filter列A中使用ComboBox1的值选择电话品牌。

Here's what I have so far: 这是我到目前为止的内容:

Option Explicit 
Sub AdvFilter() 
    Dim lw As Long 
    Dim lr As Long 
    lw = Range("A" & Rows.Count).End(xlUp).Row 
    Range("A2:A" & lw).AdvancedFilter Action:=xlFilterCopy, CopyToRange:=Range("H1"), Unique:=True 
End Sub 

Private Sub ComboBox1_Change() 
    Dim lr As Long 
    Dim Sel As String 
    lr = Range("H" & Rows.Count).End(xlUp).Row 
    Sel = "H2:H" & lr 
    ComboBox1.ListFillRange = Sel 
End Sub 

I was able to populate comboBox1 with unique values from Column A, but I can't figure out how to filter it using the value of ComboBox1. 我能够用列A中的唯一值填充comboBox1,但是我不知道如何使用ComboBox1的值对其进行过滤。 Any help would be greatly appreciated. 任何帮助将不胜感激。

you have only got the list of phone brands so far from column A and written them (unique brands) to column H and put it as the list of values in Combobox. 到目前为止,您只获得了A列以外的电话品牌列表,并将它们(唯一品牌)写入H列,并将其作为组合框中的值列表。 Now based on the value in combobox, you need to display the list of the phone models belonging to that brand in a column (say column I) 现在,根据组合框中的值,您需要在列中显示该品牌的手机型号列表(例如,列I)

Step 1: Get the phone brand selected from combobox. 步骤1:从组合框中选择电话品牌。 Refer this example VBA - Get Selected Value of Combobox 请参考以下示例VBA-获取组合框的选定值

Step 2: Get list of phone models under that phone brand. 步骤2:获取该手机品牌下的手机型号列表。 Let us say the phone brand is phone_brand 假设电话品牌是phone_brand

Sub getPhoneModels()
Dim iCol As Integer
iCol = 1
Dim phone_brand As String
phone_brand=getPhoneBrandFromComboBox()
For i = 1 To Range("B" & Rows.Count).End(xlUp).Row
    If StrComp(.Cells(1, i), phone_brand) = 0 Then
            .Cells(9, iCol) = .Cells(1, i)
            iCol = iCol + 1
    End If
Next i
End Sub

The above code will go through all the phone models in column B and write the ones with brand value as phone_brand in the column I (9) 上面的代码将遍历B列中的所有电话型号,并将具有品牌价值的phone_brand作为phone_brand第一列(9)中。

getPhoneBrandFromComboBox() function is the function written in first step using the help given in link. getPhoneBrandFromComboBox()函数是第一步使用链接中给出的帮助编写的函数。 This function returns the phone brand selected using the comboBox 此功能返回使用comboBox选择的电话品牌

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM