2016-11-15 163 views
1

我有這個代碼,當我點擊我的列表框中的項目時,我正在使用它來搜索範圍。我從來沒有通過列表框循環,並想知道如何添加一個循環來執行我所需要的,而無需單擊列表框中的每個項目。這裏是我使用的代碼:Excel VBA通​​過列表框循環

Sub FindListValue() 

Dim FirstAddress As String 
Dim rSearch As Range 'range to search 
Dim c As Range 

With Sheets("PN-BINS") 
    Set rSearch = .Range("B1", .Range("B65536").End(xlUp)) 
End With 

Dim i As Long 

' loop through all items in ListBox1 
For i = 0 To Me.ListBox1.ListCount - 1 

    ' current string to search for 
    strFind = Me.ListBox1.List(i) 

    With rSearch 
    Set c = .Find(strFind, LookIn:=xlValues, LookAt:=xlWhole) 
    If Not c Is Nothing Then 'found it 
    c.Select 
    Me.ListBox1.AddItem strFind & " | " & c.Offset(0, -1).Value, Me.ListBox1.ListIndex + 1 
    Me.ListBox1.RemoveItem (Me.ListBox1.ListIndex) 
    'Exit Sub 

    Else: 'MsgBox strFind & " is not listed!" 'search failed 

    End If 
    End With 

    ' the rest of your code logics goes here... 
Next i 

End Sub 
+0

我不確定我是否理解這個問題。你已經從你的列表框中選擇了一些東西,並且你想使用這個值來找到某個範圍內的東西(你可以通過循環或Find方法來完成) - 那麼點擊列表框中的每個項目進入它? – jsheeran

+0

當我單擊列表框中的項目時,如果單擊每個項目,我將使用範圍內的搜索信息替換該行,該範圍工作得很好。我想要做的是不需要單擊列表框中的所有項目,只需搜索列表框中的每一行即可。如果發現,請更換線路。如果沒有找到,就什麼也不做。我希望我有道理。 – Noob2Java

+0

@ user3340949嘗試下面我的答案中的代碼,看看它是否適用於您 –

回答

1

爲了遍歷該ListBox1的所有項目,請使用以下循環:

Dim i     As Long 

' loop through all items in ListBox1 
For i = 0 To Me.ListBox1.ListCount - 1 

    ' current string to search for 
    strFind = Me.ListBox1.List(i) 

    ' the rest of your code logics goes here... 


Next i 

順便說一句,這是更好,如果你定義在你的rSearch範圍下面的方式(不使用ActivateActiveSheet

With Sheets("PN-BINS") 
    Set rSearch = .Range("B1", .Range("B65536").End(xlUp)) 
End With 

編輯1:整碼

Sub FindListValue() 

Dim FirstAddress  As String 
Dim rSearch    As Range 'range to search 
Dim c     As Range 
Dim i     As Long 

With Sheets("PN-BINS") 
    Set rSearch = .Range("B1", .Range("B65536").End(xlUp)) 
End With 

' loop through all items in ListBox1 
For i = 0 To Me.ListBox1.ListCount - 1 

    strFind = Me.ListBox1.List(i) ' string to look for 

    Set c = rSearch.Find(strFind, LookIn:=xlValues, LookAt:=xlWhole) 

    ' current ListBox1 item is found 
    If Not c Is Nothing Then 
     Me.ListBox1.AddItem strFind & " | " & c.Offset(0, -1).Value, i + 1 
     Me.ListBox1.RemoveItem (i) 

     ' ****** not sure if you want to use the line below ? ****** 
     Exit Sub 
    Else 
     MsgBox strFind & " is not listed!" 'search failed 
    End If 

Next i 

End Sub 
+0

感謝您的幫助。我根據您的建議修改了我剛纔所做的更改。我在'c.select'上遇到錯誤。我沒有正確地放置代碼嗎? – Noob2Java

+0

@ user3340949你不應該在你的帖子中使用你在答案中得到的代碼,通過這個你正在處理你的帖子。你應該接受你得到的答案,並在他們旁邊標記「v」,或者(如果他們不工作)評論他們仍然給你一個錯誤的地方。無論如何,沒有必要使用這一行'c.Select',你可以將其刪除 –

+1

感謝您的幫助,代碼工作得很好。感謝編輯後的信息,我會確保將來不會這樣做。 – Noob2Java