在表单中调用模块和类 [英] Calling a Module and a Class within a Form
问题描述
我有一个 Employee 类,我在其中调用我的数据库连接模块进行查询.
I have an Employee class where I call my database connection Module to make a query.
我收到编译错误:预期的函数或变量",我不明白,因为我在表单顶部设置了 empObj
.
I am getting "Compile Error: Expected function or variable", which I'm not understanding, because I have the empObj
set at the top of the form.
我想从 Employee.getEmployee 方法返回值.有人可以告诉我如何从我的表单中调用 Employee 类吗?我必须先导入课程吗?我不相信 VB6 支持 Imports
关键字.
I would like to return the value from the Employee.getEmployee method. Can someone please show me how to call the Employee class from my form? Do I have to import the class first? I don't believe VB6 supports the Imports
keyword.
这是我的表格:
Option Explicit
Private empObj As New Employee
Private Sub Form_Load()
'For testing only
MsgBox (empObj.getEmployee)
End Sub
这是我的课:
Public Sub getEmployee()
'ConnectSQL is a database connection
return ConnectSQL
End Sub
这是模块:
Public Function ConnectSQL()
Set SQLMyconn = New ADODB.Connection
Set SQLRecset = New ADODB.Recordset
SQLMyconn.Open "Driver={MySQL ODBC Client Interface};ServerName=localhost;dbq=@testdb"
End Function
推荐答案
你想做的基本shell是这样的:
The basic shell of what you want to do is like this:
Option Explicit
Private empObj As Employee
Private Sub Form_Load()
Set empObj = New Employee
MsgBox empObj.getEmployee
End Sub
Public Function getEmployee() As String
getEmployee = ConnectSQL
End Function
Public Function ConnectSQL() As String
Set SQLMyconn = New ADODB.Connection
Set SQLRecset = New ADODB.Recordset
SQLMyconn.Open "Driver={MySQL ODBC Client Interface};ServerName=localhost;dbq=@testdb"
ConnectSQL = "data from your DB lookup"
End Function
几乎每一行都与您发布的内容不同,因此请仔细查看代码.
Almost every line is different than what you posted, so carefully look at the code.
根据评论,这里是如何修改代码以返回连接对象:
Based on a comment, here's how to modify the code to return a connection object:
Option Explicit
Private empObj As Employee
Private Sub Form_Load()
Set empObj = New Employee
MsgBox empObj.getEmployee
Dim MyConnection As ADODB.Connection
Set MyConnection = ConnectSQL()
'you can grab and use the connection in your form, too.
End Sub
Public Function getEmployee() As String
Dim MyConnection As ADODB.Connection
Set MyConnection = ConnectSQL()
'use the connection to grab data
getEmployee = "data from your DB lookup"
End Function
Public Function ConnectSQL() As ADODB.Connection
Set ConnectSQL = New ADODB.Connection
ConnectSQL.Open "Driver={MySQL ODBC Client Interface};ServerName=localhost;dbq=@testdb"
End Function
完成连接后不要忘记关闭连接.总结一下变化:
Don't forget to close your connection after you are done with it. To sum up the changes:
- empObj - 您应该分别声明和实例化您的对象.
- MsgBox - 不需要 ().
- Functions vs Subs - 第一个返回数据,第二个不返回.确保声明函数的返回类型.
- return - 此语句已过时,不能满足您的要求.相反,为函数的名称分配一个值.
这篇关于在表单中调用模块和类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!