NaN
NaN

Reputation: 577

Calling a Module and a Class within a Form

I have an Employee class where I call my database connection Module to make a query.

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.

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.

This is my form:

Option Explicit

Private empObj As New Employee

Private Sub Form_Load()
  'For testing only
  MsgBox (empObj.getEmployee)
End Sub

This is my class:

Public Sub getEmployee()
  'ConnectSQL is a database connection
  return ConnectSQL
End Sub

And this is the module:

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

Upvotes: 0

Views: 1040

Answers (1)

Brian M Stafford
Brian M Stafford

Reputation: 8868

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.

EDIT:

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:

  1. empObj - you should declare and instantiate your objects separately.
  2. MsgBox - no need for the ().
  3. Functions vs Subs - the first returns data, the second does not. Make sure you declare the return type of a function.
  4. return - this statement is obsolete and doesn't do what you want. Instead, assign a value to the name of the function.

Upvotes: 3

Related Questions