-2

以下“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
4

3 回答 3

0

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

于 2013-08-08T23:11:22.007 回答
0

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

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
于 2018-03-11T15:45:27.030 回答
0

这可以用 4 个类模块模拟“覆盖函数”:Functions、IFunction、FunctionAdd、FunctionSubtract。

类模块功能:

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

接口函数:

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

类模块函数添加:

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)

当然,这对于一个功能来说是乏味的。如果您在许多类中有很多要覆盖的功能,我可能会很有用。

于 2016-08-01T16:45:39.167 回答