覆盖函数

时间:2013-08-08 22:48:37

标签: vba excel-vba excel

以下“aMacro”返回错误“检测到模糊名称”我理解为什么。任何人都知道一种覆盖第一个定义的方法,并且只使用函数内部的定义,以便aFunction将返回x - y?

除了更改名称外。

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 个答案:

答案 0 :(得分:0)

一个函数可以是PrivatePublic,但范围始终是整个模块。

答案 1 :(得分:0)

这可以模拟"覆盖功能"有4个课程模块: 函数,IFunction,FunctionAdd,FunctionSubtract。

类模块功能:

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

接口IFunctions:

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

类模块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

类模块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

你可以用这个来测试:

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

当然,这对于一个功能来说是乏味的。 我可能很有用,你可以在很多类中覆盖很多函数。

答案 2 :(得分:0)

尝试添加函数中的Optional值。如果调用中未包含可选值,则它不会是函数中的引用。

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