2016-05-08 16 views
1

は、私は次のコードのビットを持っているユーザーフォームが含まれています:excel 2010 vbaどのようにリストボックスを宣言できますか?

Private Sub RemoveRecipientCommandButton_Click() 
    Application.ScreenUpdating = False 
    Dim intCount As Integer 
    For intCount = RecipientsListBox.ListCount - 1 To 0 Step -1 
    If RecipientsListBox.Selected(intCount) Then RecipientsListBox.RemoveItem (intCount) 
    Next intCount 
    Application.ScreenUpdating = True 
End Sub 

このコードは複数選択1であるリストボックス上で実行される - fmMultiSelectMulti、とうまく動作します。パラメータが渡されるようにするときに問題が発生するので、複数のListBoxで同じサブを使用できます。私が試した:

Private Sub RemoveRecipientCommandButton_Click() 
    Application.ScreenUpdating = False 
    RemoveSelected (RecipientsListBox) 
    Application.ScreenUpdating = True 
End Sub 

Private Sub RemoveSelected(LB As ListBox) 
    Dim intCount As Integer 
    For intCount = LB.ListCount - 1 To 0 Step -1 
    If LB.Selected(intCount) Then LB.RemoveItem (intCount) 
    Next intCount 
End Sub 

で、私も試してみた:

Private Sub RemoveSelected(LB As MSForms.ListBox) 

Private Sub RemoveSelected(LB As ListObject) 

としてRemoveSelectedコードビーイングの残りの部分と同じ。このコードのこれらの形式はすべてエラー424 - オブジェクトが必要です。私は決してExcelプロではないので、私の主な関心事はここで働くコードを見つけることです - これを、必要ならば、コードを書かなくても複数のListBoxで使用できるものにしたいと思っています各ListBoxで新しい誰かが私を正しい方向に向けることができたら、私が得ることができるすべての助けに感謝します。ありがとう。

+0

Subsを宣言するために 'Private'を使用する場合、それらは同じモジュールまたはuserform-moduleにある必要があります。 –

答えて

4

複数の問題があります。

  1. CallなしSub Sを呼び出し、かっこ内のパラメータをラップしないでください。 Call RemoveSelected(RecipientsListBox)またはRemoveSelected RecipientsListBoxのいずれかです。

  2. デフォルトの手渡しパラメータはByRefですが、ここではこれはできません。したがって、ByValを使用する必要があります。

  3. 正しいタイプはMSForms.ListBox

コード:

Private Sub RemoveRecipientCommandButton_Click() 
Application.ScreenUpdating = False 
RemoveSelected RecipientsListBox 
'Call RemoveSelected(RecipientsListBox) 
Application.ScreenUpdating = True 
End Sub 



Private Sub RemoveSelected(ByVal LB As MSForms.ListBox) 
Dim intCount As Integer 
For intCount = LB.ListCount - 1 To 0 Step -1 
    If LB.Selected(intCount) Then LB.RemoveItem intCount 
Next intCount 
End Sub 

編集:

@Patrick Lepelletierに述べたように、ByRef、この場合に可能です。私はそう

Private Sub RemoveSelected(LB As MSForms.ListBox) 
Dim intCount As Integer 
For intCount = LB.ListCount - 1 To 0 Step -1 
    If LB.Selected(intCount) Then LB.RemoveItem intCount 
Next intCount 
End Sub 

も動作します ByRef

で問題の原因をローカル変数に保存されているSet oListboxControl = RecipientsListBox : RemoveSelected oListboxControlControlオブジェクトを持っていました。

+0

これは素晴らしいAxelで動作します。ありがとうございました! – dubyarly

+2

'Byref'はなぜできませんか?私は間違いなくこの状況で 'Byref'を使うでしょう。私は何度もそれをやりました。 –

+0

@Patrick Lepelletier:はい、そうです。私のサプリメントを参照してください。 –

関連する問題