2017-07-11 56 views
0

我有下面的子根据三个条件找到一个单元格。VBA用户窗体列表框和文本框

Private Sub FindEstimate_Click() 

Dim i As Long 

i = 5 
Do 
    If Cells(i, 1) = TextBox1 And Cells(i, 6) = ListBox1 And Cells(i, 9) = ListBox2 Then 
     Cells(i, 1).Select 
    End If 
    i = i + 1 
Loop Until Cells(i, 1) = TextBox1 And Cells(i, 6) = ListBox1 And Cells(i, 9) = ListBox2 

End Sub 

它根本行不通,我怀疑它与Loop Until语句有关。

+0

究竟是你想检查与'细胞(我,6)= ListBox1'和'什么细胞(I,9)= ListBox2'? ListBox中的'Selected'项目? –

+0

'Range.Find'可能比循环更好。 –

+0

我正在尝试根据三个条件查找一行的第一个单元格。首先是估算数字(例如“8888”“8889”)。另一个是(第6列),是网站(例如Facebook *,Twitter *,Pinterest *)。第9栏是月份(6/16,7/16-7/17)。 –

回答

1

您使用Find功能,并遍历所有Find结果列“A”的好(如果有与TextBox1.Value多个匹配),直到你能还找到一个匹配ListBox1.ValueListBox2.Value

为此,您将使用Do <→Loop While Not FindRng Is Nothing And FindRng.Address <> FirstAddres循环。

代码

Option Explicit 

Private Sub FindEstimate_Click() 

Dim Rng As Range 
Dim FindRng As Range 
Dim FirstRng As Range 
Dim FirstAddress As String 


Set Rng = Range("A5:A" & Cells(Rows.Count, "A").End(xlUp).Row) 

With Rng 
    Set FindRng = .Find(what:=Me.TextBox1.Value, LookIn:=xlValues, _ 
         lookat:=xlWhole, searchorder:=xlByRows, searchdirection:=xlNext) 

    If Not FindRng Is Nothing Then ' find was successful 
     ' Set FirstRng = FindRng 
     FirstAddress = FindRng.Address 

     Do 
      If FindRng.Offset(, 5).Value = Me.ListBox1.Value And FindRng.Offset(, 8).Value = Me.ListBox2.Value Then 
       FindRng.Select ' <-- not sure why you need to select it 
       Exit Do 
      End If 
      Set FindRng = .FindNext(FindRng) 
     Loop While Not FindRng Is Nothing And FindRng.Address <> FirstAddress 

    Else ' Find faild to find the value in TextBox1 
     MsgBox "Unable to find " & Me.TextBox1.Value & " at column A" 
    End If 
End With 

End Sub 
相关问题