vendredi 26 août 2016

Excel VBA Select a row based on its multi-column data matching criteria in multiple userform comboboxes

This is a solution I am interested in implementing but I am unsure of my syntax, I will provide an example of what I have below. I believe a similar result can be found using an AutoFilter method, but I wish to avoid this if possible. I am basing my attempts so far on a suggestion from Søren Holten Hansen in this post that uses nested if statements to return the row number that matches criteria contained within TextBoxes.

For background, I currently have a UserForm1 that contains five ComboBoxes and two Command Buttons.

Each ComboBox pre-populates with the contents of a named range housing data that corresponds to data on Sheet1, such as "Fruits" in ComboBox1 and Column A of Sheet1, "Vegetables" in ComboBox2 and Column B of Sheet1, and so on.

My goal is to use nested If statements when CommandButton1 is clicked to find and Select the entire row on Sheet 1 which contains an exact match to the value of each ComboBox. For example, if the user selects 'Apple' from ComboBox1, 'Potato' from ComboBox2, 'Farm' from ComboBox 3, 'Monkey' from ComboBox4, and 'Supermarket' from ComboBox5, the entire row on Sheet1 that contains 'Apple' in Column A, 'Potato' in Column B, 'Farm' in Column C', 'Monkey' in Column D, and 'Supermarket' from Column E is then selected.

What I have so far is the following, assigned to 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

I believe the desired result can be achieved using nested If statements, but I am unsure of my formatting in this example.

Thank you.

Aucun commentaire:

Enregistrer un commentaire