简体   繁体   English

在 VBA 中调用类函数时出错

[英]Error calling class function in VBA

I have this class module inside my Access database:我的 Access 数据库中有这个类模块:

Option Compare Database

Public Event BeforeCalc()

Public Sub Calculate(ByVal i As Integer, ByVal y As Integer)
    RaiseEvent BeforeCalc
    Calculate = i + y
End Sub


Private Sub Class_Initialize()
    Debug.Print "Inside construcotr"
End Sub

Then, inside a custom form:然后,在自定义表单中:

Option Compare Database

Private WithEvents math As MyMath

Private Sub btnCalculate_Click()
    Dim result As Integer
    Set result = math.Calculate(CInt(txtI.Text), CInt(txtY.Text))
End Sub

Private Sub Form_Load()
    Set math = New MyMath
End Sub

Private Sub math_BeforeCalc()
    MsgBox "About to Calc!", vbInformation
End Sub

When I click the form button btnCalculate I got this error at math.Calculate:当我单击表单按钮 btnCalculate 时,我在 math.Calculate 中收到此错误:

"Compile error. Expected function or variable." “编译错误。预期的函数或变量。”

What's wrong with my code?我的代码有什么问题?

Since it is a function so it should return something, in your case an integer and also you should specify the Function keyword.因为它是一个函数,所以它应该返回一些东西,在你的情况下是一个整数,你也应该指定 Function 关键字。

replace the code :替换代码:

Public Sub Calculate(ByVal i As Integer, ByVal y As Integer)
     RaiseEvent BeforeCalc
     Calculate = i + y
End Sub

with :与:

Public Function Calculate(ByVal i As Integer, ByVal y As Integer) as Integer
    RaiseEvent BeforeCalc
    Calculate = i + y
End Sub

You have defined Calculate as a Sub, try defining it as a Function:您已将计算定义为子函数,请尝试将其定义为函数:

Public Function Calculate(ByVal i As Integer, ByVal y As Integer) as Integer
    RaiseEvent BeforeCalc
    Calculate = i + y
End Function

Also, don't set the result:另外,不要set结果:

Private Sub btnCalculate_Click()
    Dim result As Integer
    result = math.Calculate(CInt(txtI.Text), CInt(txtY.Text))
End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM