excel vba: Special Types - Functions as Arguments of Functions

后端 未结 3 1153
梦谈多话
梦谈多话 2020-12-07 23:03

There is no special type for functions in VBA. It is hard for me to see how to add functions as arguments to functions in Excel VBA.

What I am trying to accomplish i

3条回答
  •  心在旅途
    2020-12-07 23:55

    It is possible to pass a function as an argument, and get exactly the behaviour you're after, but it's a bit hacky. This is achieved by exploiting the default property of a class,

    Create a class myFunction containing your function

    Public Function sayHi(ByVal s As String) As String
        sayHi = "Hi " & s
    End Function
    

    Export it, and open the .cls file in a text editor

    You should see somewhere in the file, a line that defines your function

    Public Function sayHi(ByVal s As String) As String
    

    Beneath it, add the line Attribute Value.VB_UserMemId = 0, so that now it looks like this:

    Public Function sayHi(ByVal s As String) As String
    Attribute Value.VB_UserMemId = 0
        sayHi = "Hi " & s
    End Function
    

    What you've done here is to mark sayHi as the default property of the class. Now you can call the function by the class object alone class(args), rather than class.function(args)

    Save the amended file and import it into your VBA project

    Test module

    Sub test()
        Dim parameterFunction As Object         'this is what we'll be passing to our routine
        Set parameterFunction = New myFunction  'create instance of the function object
        MsgBox f(parameterFunction, "Greedo")
    End Sub
    
    Function f(ByVal g As Object, ByVal x As String) As String
            f = g(x)
    End Function
    

    *NB, this way you can pass any function; but you may instead specify ByVal g As IStringFunction to get only the subset with the correct interface as per Gary McGill's answer

提交回复
热议问题