使用vba在excel中搜索不同的项目

时间:2016-07-20 07:23:47

标签: vba excel-vba excel

我想在输入" 2"在查找什么列并点击搜索我的第一个项目列需要显示葡萄,我的第二个项目列显示香蕉。

Userform Worksheet data

Private Sub CommandButton1_Click()
row_number = 0
Do
DoEvents
row_number = row_number + 1
item_in_review = Sheets("SHEET1").Range("A" & row_number)
If item_in_review = TextBox1.Text Then
   TextBox2.Text = Sheets("SHEET1").Range("B" & row_number)
   'want to know which code I want to use in textbox3.text to find next repetation
    TextBox3.Text = Sheets("SHEET1").Range("B" & row_number)

   End If
Loop Until item_in_review = ""
End Sub

1 个答案:

答案 0 :(得分:2)

这可以使用Range.FindRange.FindNext方法完成。

Private Sub CommandButton1_Click()
    Dim rSearch As Range
    Dim rFound As Range

    With Sheets("SHEET1")
        Set rSearch = .Range("A1", .Range("A" & Rows.Count).End(xlUp))

        Set rFound = rSearch.Find(What:=TextBox1.Text, LookIn:=xlValues)

        If rFound Is Nothing Then
            TextBox2.Value = ""
        Else
            TextBox2.Value = rFound.Offset(0, 1).Value

            Set rFound = rSearch.FindNext(rFound)

            If rFound Is Nothing Then
                TextBox3.Value = ""
            Else
                TextBox3.Value = rFound.Offset(0, 1).Value
             End If

        End If
    End With

End Sub

您的代码也可以进行一些重构。

Private Sub CommandButton1_Click()
    Dim row_number As Long
    TextBox2.Value = ""
    TextBox3.Value = ""

    With Sheets("SHEET1")
        Do
            row_number = row_number + 1
            item_in_review = .Range("A" & row_number)

            If item_in_review = TextBox1.Text Then
                If TextBox2.Text = "" Then
                    TextBox2.Text = .Range("B" & row_number)
                Else
                    TextBox3.Text = .Range("B" & row_number)
                    Exit Do
                End If

            End If
        Loop Until item_in_review = ""
    End With
End Sub