将ComboBox作为参数传递给Sub或Function

时间:2019-06-26 02:57:24

标签: excel vba function combobox

我在将ComboBox作为子进程中的参数传递时遇到问题。在使用子流程排序每个ComboBox的内容之前,我现在尝试的是减少代码。

我解释: 表单包含N个ComboBox(1、2,... N),每个表格列的内容均被填充。例如:

Set NColumn = TStaff.ListColumns("NameStaff").DataBodyRange
Me.ComboBox1.List = NColumn.value
SortComboBox1

Set IDColumn = TStaff.ListColumns("IDStaff").DataBodyRange
Me.ComboBox2.List = IDColumn.value
SortComboBox2

...

SortComboBoxN

用于订购每个组合框内容的代码如下:

Private Sub SortComboBox1()
Dim i As Long
Dim j As Long
Dim sTemp As String
Dim LbList As Variant

LbList = Me.ComboBox1.List

For i = LBound(LbList, 1) To UBound(LbList, 1) - 1
    For j = i + 1 To UBound(LbList, 1)
        If LbList(i, 0) > LbList(j, 0) Then

            sTemp = LbList(i, 0)
            LbList(i, 0) = LbList(j, 0)
            LbList(j, 0) = sTemp
        End If
    Next j
Next i

Me.ComboBox1.Clear

Me.ComboBox1.List = LbList
End Sub

Private Sub SortComboBox2()
...
End sub

...

Private Sub SortComboBoxN()
...
End sub

我要寻找的是一个子进程,该子进程接收任何ComboBox(或其内容)作为参数,并避免重复相同的代码来对每个ComboBox进行排序。

我的第一种方法是这样,但是会出现“错误424”(需要一个对象):

Modulo1:

Public CBox As ComboBox

UserForm(代码)

Private Sub UserForm_Initialize()
...
Me.ComboBox1.List = NColumn.value
SortCBox (Me.ComboBox1)
Me.ComboBox2.List = IDColumn.value
SortCBox (Me.ComboBox2)
End Sub

Private Sub SortCBox(ByRef CBox As MSForms.ComboBox)
Dim i As Long
Dim j As Long
Dim sTemp As String
Dim LbList As Variant

LbList = CBox.List 

For i = LBound(LbList, 1) To UBound(LbList, 1) - 1
    For j = i + 1 To UBound(LbList, 1)
        If LbList(i, 0) > LbList(j, 0) Then
            sTemp = LbList(i, 0)
            LbList(i, 0) = LbList(j, 0)
            LbList(j, 0) = sTemp
        End If
    Next j
Next i

CBox.Clear

CBox.List = LbList
End Sub

问题出在哪里? *如果有人采用其他方法,谢谢您的建议

1 个答案:

答案 0 :(得分:0)

您的问题在于如何调用子例程

SortCBox (Me.ComboBox1) ' <-- Wrong!

,它将根据默认值评估Me.ComboBox1,因此很可能会使用字符串参数调用SortCBox-这不是您想要的。

您应该通过以下方式调用子例程

SortCBox Me.ComboBox1 ' <-- Right!

它将按预期通过。

简单说明由Microsoft(https://docs.microsoft.com/en-us/office/vba/language/concepts/getting-started/using-parentheses-in-code)提供。