Excel 按ComboBox1创建下拉列表并筛选所需列

Excel 按ComboBox1创建下拉列表并筛选所需列,excel,vba,Excel,Vba,我一直在使用一个工作表,其中我通过“数据验证”创建了一个手动下拉列表,并使用下面的代码筛选列 Private Sub Worksheet_Change(ByVal Target As Range) Dim lastrow As Long lastrow = Cells(Rows.Count, "I").End(xlUp).Row With Me If Not Intersect(Target, .Range("I13")) Is Nothing T

我一直在使用一个工作表,其中我通过“数据验证”创建了一个手动下拉列表,并使用下面的代码筛选列

Private Sub Worksheet_Change(ByVal Target As Range)
 Dim lastrow As Long
 lastrow = Cells(Rows.Count, "I").End(xlUp).Row
 With Me
 If Not Intersect(Target, .Range("I13")) Is Nothing Then
 If Target.Value <> "" Then
 .AutoFilterMode = False
 .Range("I15:I" & lastrow).AutoFilter field:=1, Criteria1:=Target.Value
 End If
 End If
 End With
End Sub
我想把这两个代码合并成一个来工作。我试过了,但失败了

Private Sub Worksheet_Change(ByVal Target As Range)
 
 Dim lastrow As Long
 
 With Sheets("Sheet1").Range("I15:I" & lastrow)
    v = .Value
End With
With CreateObject("scripting.dictionary")
    .comparemode = 1
    For Each e In v
        If Not .exists(e) Then .Add e, Nothing
    Next
    If .Count Then Sheets("Sheet1").ComboBox1.List = Application.Transpose(.keys)
End With
 
 lastrow = Cells(Rows.Count, "I").End(xlUp).Row
 
 With Me
 If Not Intersect(Target, .Range("I1")) Is Nothing Then
 If Target.Value <> "" Then
 .AutoFilterMode = False
.Range("I15:I" & lastrow).AutoFilter field:=1, Criteria1:=Target.Value
 End If
 End If
 End With
Private子工作表\u更改(ByVal目标作为范围)
最后一排一样长
带图纸(“图纸1”)。范围(“I15:I”和lastrow)
v=0.0值
以
使用CreateObject(“scripting.dictionary”)
.comparemode=1
对于v中的每个e
如果不存在,则添加e,无任何内容
下一个
如果.Count然后是Sheets(“Sheet1”).ComboBox1.List=Application.Transpose(.keys)
以
lastrow=单元格(Rows.Count,“I”).End(xlUp).Row
和我一起
如果不相交(目标,.Range(“I1”)则为零
如果Target.Value为“”,则
.AutoFilterMode=False
.Range(“I15:I”&lastrow)。自动筛选字段:=1,准则1:=Target.Value
如果结束
如果结束
以

您不再需要
工作表\u Change
事件,因为您不是从数据验证单元格捕获值,而是从
组合框1
捕获值。将此代码(未测试)粘贴到
表1
代码区域。从
组合框1
中选择项目时,以下代码将自动过滤。如果需要,还可以使用
命令按钮
运行此代码

如果你面临问题,请告诉我

Private Sub ComboBox1_Click()
    If ComboBox1.ListIndex = -1 Then Exit Sub
    
    Dim ws As Worksheet
    Set ws = Sheet1
        
    With ws
        .AutoFilterMode = False
        
        LastRow = .Range("I" & .Rows.Count).End(xlUp).Row
        
        .Range("I15:I" & LastRow).AutoFilter Field:=1, Criteria1:=ComboBox1.Value
    End With
End Sub

您还需要加载
组合框1
。您可以使用
命令按钮
或使用
工作簿打开()
事件来执行此操作。

您面临的问题是什么?Siddharth Rout,我想将它们合并到一个两者都应该使用的对象中(ByVal Target As Range)/Automate仅此而已,我还不了解您的要求。暂时忘记合并吧。你能解释一下你想要实现什么吗?先生,实际上我希望ComboBox1加载该范围的唯一值I12:I最后一行,当我从ComboBox1中选择任何值时,Col“I”应该过滤ComboBox1中可用的类似值。我添加了一张图片。非常感谢您提供的解决方案。
Private Sub ComboBox1_Click()
    If ComboBox1.ListIndex = -1 Then Exit Sub
    
    Dim ws As Worksheet
    Set ws = Sheet1
        
    With ws
        .AutoFilterMode = False
        
        LastRow = .Range("I" & .Rows.Count).End(xlUp).Row
        
        .Range("I15:I" & LastRow).AutoFilter Field:=1, Criteria1:=ComboBox1.Value
    End With
End Sub