简体   繁体   English

Excel VBA遍历列表框

[英]Excel VBA loop through listbox

I have this code that I am using to search a range when I click the item in my listbox. 单击列表框中的项目时,我有用于搜索范围的这段代码。 I have never looped through a listbox and want to know how I add a loop to perform what I need without clicking each item in the listbox. 我从未遍历过列表框,并且想知道如何添加循环来执行所需的操作而无需单击列表框中的每个项目。 Here is the code I am using: 这是我正在使用的代码:

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

In order to loop through all items in the ListBox1 , use the following loop: 为了循环遍历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

BTW , it's better if you define your rSearch range in the following way (without using Activate and ActiveSheet ) 顺便说一句,最好以以下方式定义rSearch范围(不使用ActivateActiveSheet

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

Edit 1 : Whole code 编辑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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM