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 

此代码运行在MultiSelect 1 – fmMultiSelectMulti的列表框上,工作正常。 当我尝试允许parameter passing给它的时候,问题出现了,所以我可以在多个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代码是相同的。 所有这些代码的forms抛出错误424 – 所需的对象。 我不是一个Excel专业人员,所以我主要关心的是find可以工作的代码 – 我希望能够将这个function变成我可以在多个ListBox上使用的function,如果需要的话,无需编写代码作为每个ListBox的新。 如果有人甚至可以把我指向正确的方向,我会很感激任何帮助,我可以得到。 谢谢。

这里有多个问题。

  1. 不要将参数封装在调用Sub s without Call括号中。 所以要么Call RemoveSelected(RecipientsListBox)RemoveSelected RecipientsListBox

  2. 默认的方式来移交参数是ByRef但在这里是不可能的。 所以需要使用ByVal

  3. 正确的types是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是可能的。 我有Control对象存储在一个局部variablesSet oListboxControl = RecipientsListBox : RemoveSelected oListboxControl是什么引起与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 

也将工作。