[英]VBA Userform ListBox and TextBox
我有以下子代碼可根據三個條件找到一個單元格。
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直到語句有關。
您最好使用Find
函數,並遍歷“ A”列中的所有Find
結果(以防與TextBox1.Value
有多個匹配項),直到您還能夠找到與ListBox1.Value
和ListBox2.Value
匹配的項ListBox2.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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.