VBA函数参数列表选择

时间:2011-03-17 13:56:06

标签: vba excel-vba excel-2007 excel

我希望做以下事情:

    Public Function myFunc(vArg1 as string, vArg2 as string, vArg3 as ["A","B","C"])


    End Function

用户在调用vArg3时获取vArg3的下拉列表。这将类似于以下内容:

            Public Sub Main()
                Call StrComp("A", "B", vbTextCompare)
            End Sub

可以从预定义的列表或函数的参数中选择vbTextCompare。

由于

2 个答案:

答案 0 :(得分:11)

这就是所谓的枚举。这是一个简单的例子:

Public Enum DayOfWeek
    Monday = 1
    Tuesday = 2
    Wednesday = 3
    Thursday = 4
    Friday = 5
    Saturday = 6
    Sunday = 7
End Enum

Public Function GetDrinkSpecial(day As DayOfWeek) As String

    Select Case day
        Case DayOfWeek.Monday
            GetDrinkSpecial = "$1 Tap Domestics"
        Case DayOfWeek.Tuesday
            GetDrinkSpecial = "2 for 1 Rail Mixers"
        Case DayOfWeek.Wednesday
            GetDrinkSpecial = "$2 You-Call-Its"
        Case DayOfWeek.Thursday
            GetDrinkSpecial = "$1 Bush Bottles"
        Case DayOfWeek.Friday
            GetDrinkSpecial = "$3 Greenies"
        Case DayOfWeek.Saturday
            GetDrinkSpecial = "No Specials, Doh!"
        Case DayOfWeek.Sunday
            GetDrinkSpecial = "No Specials, Doh!"
        Case Else
            GetDrinkSpecial = "No Specials, Doh!"
    End Select
End Function

Public Sub TestIt()

    MsgBox GetDrinkSpecial(Monday)
    MsgBox GetDrinkSpecial(Tuesday)
    MsgBox GetDrinkSpecial(Wednesday)
    MsgBox GetDrinkSpecial(Thursday)
    MsgBox GetDrinkSpecial(Friday)
    MsgBox GetDrinkSpecial(Saturday)
    MsgBox GetDrinkSpecial(Sunday)
End Sub

这将在VBA编辑器中调用函数时获得所需的“下拉”效果。但是,如果要从excel单元格公式中调用“GetDrinkSpecial”,则无法访问枚举,并且需要专门传递枚举的long值。

答案 1 :(得分:2)

不完全按你提问的方式。

首先,您必须为模块中的可能选项定义“公共枚举”(它可以是相同的模块,只要它不是类模块)

Public Enum myFuncEnum
   OPTION_A
   OPTION_B
   OPTION_C
End Enum

然后,在函数定义中,您应该:

Public Function myFunc(vArg1 as string, vArg2 as string, vArg3 as myFuncEnum)

End Function

请记住,您必须将vArg3与OPTION_A,OPTION_B和OPTION_C进行比较,而不是“A”,“B”和“C”。顺便说一下,OPTION_A,OPTION_B等可以重命名以使其更有意义,但它们在整个项目中应该是唯一的。