Override a Function

2019-09-22 07:00发布

The following "aMacro" returns the error "Ambiguous name Detected" I understand why. Anybody know a way to override the first definition and and only use the definition inside of the function so that aFunction will return x - y ?

Besides changing the name.

Function aFunction(x As Integer, y As Integer) As Integer

    aFunction = x + y

End Function



Sub aMacro()

    Function aFunction(x As Integer, y As Integer) As Integer
        aFunction = x - y
    End Function
    MsgBox aFunction(4, 3)

End Function

3条回答
成全新的幸福
2楼-- · 2019-09-22 07:11

This can simulate "override function" with 4 class modules: Functions, IFunction, FunctionAdd, FunctionSubtract.

class module Functions:

Function aFunction(x As Integer, y As Integer) As Integer
    aFunction = x + y
End Function

interface IFunctions:

Function aFunction(x As Integer, y As Integer) As Integer
End Function

class module FunctionAdd:

Implements IFunctions

Private mFunctions As Functions

Private Sub Class_Initialize()
    Set mFunctions = New Functions
End Sub

Private Sub Class_Terminate()
    Set mFunctions = Nothing
End Sub

Private Function IFunctions_aFunction(x As Integer, y As Integer) As Integer
    IFunctions_aFunction = mFunctions.aFunction(x, y) ' Uses the standard aFunction
End Function

Class module FunctionSubtract:

Implements IFunctions

Private mFunctions As Functions

Private Sub Class_Initialize()
    Set mFunctions = New Functions
End Sub

Private Sub Class_Terminate()
    Set mFunctions = Nothing
End Sub

Private Function IFunctions_aFunction(x As Integer, y As Integer) As Integer
    IFunctions_aFunction = x - y ' Override aFunction, subtract values
End Function

You can test this with this:

Dim f As IFunctions
Set f = New FunctionAdd: Debug.Print f.aFunction(1, 2)
Set f = New FunctionSubtract: Debug.Print f.aFunction(1, 2)

Of course this is tedious for one function. I could be useful is you have a lot of functions to override in many classes.

查看更多
Melony?
3楼-- · 2019-09-22 07:22

A function can be Private or Public, but the scope is always the whole module.

查看更多
一纸荒年 Trace。
4楼-- · 2019-09-22 07:24

Try adding in the Optional value in the function. If the optional value isnt included in the call then it wont be references in the function.

Function aFunction(x As Integer, y As Integer, Optional override As Boolean) As Integer
    If Not override Then
        aFunction = x + y
    Else
        aFunction = x - y
    End If
End Function
Sub aMacro()
    MsgBox aFunction(4, 3)
    MsgBox aFunction(4, 3, True)
End Sub
查看更多
登录 后发表回答