2016-08-26 55 views
0

这是一个我有兴趣实现的解决方案,但我不确定自己的语法,我将提供一个我下面的示例。我相信使用AutoFilter方法可以找到类似的结果,但我希望尽可能避免这种情况。我将目前为止的尝试建立在SørenHolten Hansen的this post的建议之上,该建议使用嵌套的if语句返回与TextBoxes中包含的条件相匹配的行号。Excel VBA根据多个用户表单组合框中的多列数据匹配条件选择一行

有关背景,我现在有一个包含5组合框两个命令按钮一个UserForm1。

每个ComboBox预先填充与Sheet1上的数据对应的命名范围外壳数据的内容,例如ComboBox1中的“Fruits”和Sheet1中的“A”,ComboBox2中的“Vegetables”和Sheet1中的B列中的“Vegetables”等等。

我的目标是使用嵌套如果当点击CommandButton1的找到并选择在第1页整行其中包含精确匹配到每个组合框的值的语句。例如,如果用户从ComboBox1中选择“Apple”,从ComboBox2中选择“Potato”,在ComboBox3中选择“Farm”,在ComboBox4中选择“Monkey”,在ComboBox5中选择“Supermarket”,Sheet1上包含“Apple”的整行然后选择列A,列B中的'马铃薯',列C中的'农场',列D中的'猴'和列E中的'超市'。

我至今如下,分配给CommandButton1的:

Dim i As Long, GetRow As Long 
    For i = 2 To Sheets("Sheet1").Cells(Rows.Count, 1).End(xlUp).Row 
     If Sheets("Sheet1").Cells(i, 1).Value = Me.ComboBox1.Value Then 
      If Sheets("Sheet1").Cells(i, 2).Value = Me.ComboBox2.Value Then 
       If Sheets("Sheet1").Cells(i, 3).Value = Me.ComboBox3.Value Then 
        If Sheets("Sheet1").Cells(i, 4).Value = Me.ComboBox4.Value Then 
         If Sheets("Sheet1").Cells(i, 5).Value = Me.ComboBox5.Value Then 
        GetRow = i 
       End If 
      End If 
     End If 
    End If 
End If 
Next i 
Rows(i).EntireRow.Select 
End Sub 

我认为理想的结果可以使用嵌套的IF语句来实现,但我不能确定我在这个例子中的格式。

谢谢。

+0

我认为这会更容易使用与ADO的SQL语句。下面是MSDN为您开始的一个很好的示例:https://technet.microsoft.com/en-us/library/ee692882.aspx。基本上,您只需将组合框选项作为条件添加到SQL语句的Where子句中即可。 –

回答

0

使用Autofilter()方法Range的对象,就像如下:

Option Explicit 

Private Sub CommandButton1_Click() 
    Dim i As Long 
    Dim mySelection As Range 

    With Sheet1 
     With Range("E1", .Cells(.Rows.Count, 1).End(xlUp)) 
      For i = 1 To 5 
       .AutoFilter field:=i, criteria1:=Me.Controls("Combobox" & i) 
      Next i 
      If Application.WorksheetFunction.Subtotal(103, .Resize(, 1)) > 1 Then Set mySelection = .Offset(1).Resize(.Rows.Count - 1).SpecialCells(xlCellTypeVisible) 
     End With 
     .AutoFilterMode = False 
    End With 
    If Not mySelection Is Nothing Then mySelection.Select 
End Sub 
相关问题