2016-11-15 13 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内のすべての項目を、次のループを使用します:ここで私が使用していたコードは、あなたがあなたのrSearch範囲を定義した場合

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 

はところで、それは良いでしょう以下の方法(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