我在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
然后,在自定义表单中:
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
当我点击表格按钮btnCalculate时,我在math.Calculate收到了这个错误:
“编译错误。预期的功能或变量。”
我的代码出了什么问题?
答案 0 :(得分:2)
因为它是一个函数所以它应该返回一些东西,在你的情况下是一个整数,你也应该指定Function关键字。
替换代码:
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
答案 1 :(得分:1)
您已将Calculate定义为Sub,尝试将其定义为Function:
Public Function Calculate(ByVal i As Integer, ByVal y As Integer) as Integer
RaiseEvent BeforeCalc
Calculate = i + y
End Function
另外,不要set
结果:
Private Sub btnCalculate_Click()
Dim result As Integer
result = math.Calculate(CInt(txtI.Text), CInt(txtY.Text))
End Sub