2016-11-15 181 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