Create an ADODB connection inside a function VBA-ACCESS - ms-access

I am trying to simplify my code, having a module which contains all DB connection functions in one Access, so this is what I've already done:
Module "DB"
Public Function connect() As String
Dim cn As ADODB.connection
cn.ConnectionString = "Provider=SQLOLEDB.1;Persist Security Info=False;Initial Catalog=system;Data Source=localhost; User Id= root;Password= root;"
connect = cn
End Function
Public Function sql(cn As String, query As String) As String
Dim rs As ADODB.Recordset
cn.Open
Set rs = cn.Execute(query)
cn.Close
sql = rs
End Function
Event when I click in a button
Private Sub btn_run_Click()
conexao = connect()
result = sql(conexao, "SELECT TOP 1* FROM MIS.MP_BASE_ACOES")
End Sub
Here is what my Access as an error:
Translating to en -> "Compilation error: The type defined by the user wasn't defined"
What am I doing wrong? Is that the correct way to define a connection function?
PS: There's no error in ConnectionString, I just changed some content because it is confidential.
Edit1: Following FunThomas, I really have forgotten to mark all the references like ActiveX from my project, but it still not working, now with this error:
"Uncompatible argument ByRef"

In general, you code has the following errors:
Wrong usage of functions (Public Function connect() As String)
The SQL function is not called
The object cn is of type string, and thus it does not have the Execute procedure.
Try this and try to assign the TestMe to a button. The idea to give the ConnectionString as a separate Function is a good one:
Option Explicit
Public Function ConnectionString() As String
ConnectionString = "Provider=SQLOLEDB; Data Source=1111111111; Database=ABC; User ID=NotSA; Password=NotTheSaPwd"
End Function
Public Sub TestMe()
Dim rs As ADODB.Recordset
Dim cn As ADODB.Connection
Set cn = New ADODB.Connection
Set rs = New ADODB.Recordset
cn.Open (ConnectionString)
rs.Open "SELECT * FROM TABLE", cn
Do While Not rs.EOF
Debug.Print rs!ColumnName
rs.MoveNext
Loop
End Sub

Currently you are passing a string when your function requires a connection object. Simply change parameter types accordingly:
Public Function sql(cn As ADODB.connection, query As String) As String
Dim rs As ADODB.Recordset
cn.Open
Set rs = cn.Execute(query)
cn.Close
sql = rs
End Function

Related

Run Time Error "424" Object Required / Ms Access VBA ./ Objects are declared but still the error Could some one spot the error?

Private Sub method3_Click()
Dim conn1 As ADODB.Connection
Dim recSet As ADODB.Recordset
mySQL = "Select * from Contact"
Set conn1 = New ADODB.Connection
conn1.Provider = "Microsoft.ACE.OLEDB.12.0"
'ERROR WHEN PROGRAM REACHES THE LINE BELOW
conn1.Open (Server.Mappath("G:\Data\StudentDB.accDB"))
Set recSet = New ADODB.Recordset
recSet.Open mySQL, conn1, adOpenDynamic, adLockOptimistic
mobile = recSet.Field(3)
recSet.Close
conn1.Close
Set conn = Nothing
Set recSet = Nothing
End Sub
Server is not defined at that exact line.
You can use SET Conn1 = CurrentProject.Connection to avoid having to create a new connection from scratch.

Error setting VBA Recordset of form from ADODB.recordset

I've created a function using VBA in MS Access 2010 to execute SQL server stored procedure and return value in ADODB.Recordset Object. However, I'm not able to set the MS Access form RecordSource or Recordset with the recordset that was return from ADODB connection.
Below's you'll find the code excerpt:
Dim objRs As ADODB.Recordset
Set objRs = call_proc("mySQLProc", "param")
Set Forms("form1").Recordset = objRs
Function header of call_proc:
Public Function call_proc(procName As String, procVal As String) As ADODB.Recordset
If I iterate through the objRS and do a Debug.Print I am able to see all the records. So I know the data is there. Just don't know how to fix the error of binding the data to the form.
The line of code below returns error:
Set Forms("form1").Recordset = objRs
Any suggesting kindly accepted.
Thank you in advance.
Fixed it. The issue was in my call_proc function. When I opened the ADODB.Recordset I didn't set the cursor location. See code below where I added "' <---#####ADD THIS"
Public Function call_proc(procName As String, procVal As String) As ADODB.Recordset
' Initialize variables.
Dim cn As New ADODB.Connection
Dim objCmd As New ADODB.Command
Dim objParm1 As New ADODB.Parameter
Dim objRs As New ADODB.Recordset
Dim ServerName As String, DatabaseName As String
ServerName = "YourServerName"
DatabaseName = "YourDatabaseName"
' Specify the OLE DB provider.
cn.Provider = "sqloledb"
' Set SQLOLEDB connection properties.
cn.Properties("Data Source").Value = ServerName
cn.Properties("Initial Catalog").Value = DatabaseName
cn.CursorLocation = adUseClient ' <---#####ADD THIS
' Windows authentication.
cn.Properties("Integrated Security").Value = "SSPI"
' Set CommandText equal to the stored procedure name.
objCmd.CommandText = procName
objCmd.CommandType = adCmdStoredProc
' Open the database.
cn.Open
objCmd.ActiveConnection = cn
' Automatically fill in parameter info from stored procedure.
objCmd.Parameters.Refresh
' Set the param value.
objCmd(1) = procVal
Set call_proc = objCmd.Execute
End Function

create mysql database with vba

I use VBA mostly to access MySQL database and to downlaod data from the database into an excel worksheet. In order to open connection to MySQL server through vba i use the following code:
Public Sub OpenConnection()
Set conn = New ADODB.Connection
conn.Open GetConnectionString()
End Sub
Function GetConnectionString() As String
Dim ConnectionString$
ConnectionString$ = "DRIVER={MySQL ODBC 5.3 UNICODE Driver}; _
SERVER=localhost;DATABASE=test;USER=root;PASSWORD=google;Option=3"
GetConnectionString = ConnectionString$
End Function
my question is that is there a VBA code i can use to create a new database in MySQL server and give it a specified name?
my MySQL server is version 5.6 if it helps.
thanks for the comment Drew, I actually have other codes that enable me to enter query to MySQL database, the only this that was missing is the query to create a database if the database does not exits, anyways here is the whole code in order to create a MySQL database with VBA:
Sub create_database()
Application.Calculation = xlCalculationManual
Application.ScreenUpdating = False
Call OpenConnection
Dim RS As ADODB.Recordset
Set RS = New ADODB.Recordset
Dim Query$
Query$ = "CREATE DATABASE IF NOT EXISTS Database_name"
RS.Open Query$, conn
Set RS = Nothing
Call CloseConnection
End Sub
Public Sub OpenConnection()
Set conn = New ADODB.Connection
conn.Open GetConnectionString()
End Sub
Function GetConnectionString() As String
Dim ConnectionString$
ConnectionString$ = "DRIVER={MySQL ODBC 5.3 UNICODE Driver}; _
SERVER=localhost;DATABASE=test;USER=root;PASSWORD=google;Option=3"
GetConnectionString = ConnectionString$
End Function
Public Sub CloseConnection()
conn.Close
Set conn = Nothing
End Sub

Select query run from VBA using ADO.RecordSet object does not return a complete result

I have a MySQL DB on Localhost, which I wish to access from VBA.
I have set up the ODBC connection to MySQL, and I am able to query results.
Presently, the MySQL table has 2 rows of data which should be returned. But the "Items" in "Recordset.Fields" is retaining only the last row.
My code is as follows
Public Sub Query_()
Dim connection As connection
Set connection = OpenConnection()
' Create a record-set that holds all the tasks
Dim records As ADODB.Recordset
Set records = New ADODB.Recordset
Call records.Open("SELECT pk_Client, PAN_Client FROM client", connection)
Dim result() As String
For Each Item In records.Fields
MsgBox (Item.OriginalValue)
Next
connection.Close
End Sub
Here is the OpenConnection UDF:
Private Function OpenConnection() As ADODB.connection
'Read type and location of the database, user login and password
Dim source As String, location As String, user As String, password As String
source = "taskman"
location = "localhost"
user = "root"
password = ""
'Build the connection string depending on the source
Dim connectionString As String
connectionString = "Driver={MySQL ODBC 5.3 Unicode Driver};Server=" & location & ";Database=taskman;UID=" & user & ";PWD=" & password
'Create and open a new connection to the selected source
Set OpenConnection = New ADODB.connection
Call OpenConnection.Open(connectionString)
End Function
Please help me in figuring out why the entire query result is not being retained.
Thanks
-Chinmay Kamat
This is how you'd typically code this sort of operation:
Public Sub Query_()
Dim conn As ADODB.Connection
Dim records As ADODB.Recordset, fld As ADODB.Field
Set conn = OpenConnection()
Set records = New ADODB.Recordset
records.Open "SELECT pk_Client, PAN_Client FROM client", conn
'check you got any records
If Not records.EOF Then
'loop over records
Do While Not records.EOF
Debug.Print "-------------------------"
For Each fld In records.Fields
Debug.Print fld.Name, fld.OriginalValue
Next
records.movenext 'next record
Loop
End If
records.Close
conn.Close
End Sub

Excel VBA Connection to Access 2010

I have a class that's handling my connection to an Access 2003 database. I would like to setup the same thing only for Access 07/10 .accdb files. Any help is appreciated! Thank you!
Here's a list of my references and a copy of the class object
References:
Microsoft Access 14.0 Object Library
Microsoft DAO 3.6 Object Library
ConnectionClass:
Option Explicit
Private Const DbFile = "\\server\folders\Report.mdb"
Dim OpenConn As DAO.Database
Dim ObjAccess As Object
Private Sub Class_Initialize()
On Error Resume Next
Set OpenConn = DAO.OpenDatabase(DbFile)
If Err.Number = 3024 Then MsgBox "Check connection string in the VBA StaticClass object", vbOKOnly
Set ObjAccess = CreateObject("Access.Application")
ObjAccess.Visible = False
ObjAccess.OpenCurrentDatabase (DbFile)
End Sub
Public Function runSQL(ByVal sql As String) As Recordset
Set runSQL = OpenConn.OpenRecordset(sql)
End Function
Public Function runVolumeReport(ByVal inMacro As String)
ObjAccess.DoCmd.RunMacro inMacro
End Function
Public Function closeResources()
Set ObjAccess = Nothing
OpenConn.Close
End Function
There is an issue in Class_Initialize.
On Error Resume Next
Set OpenConn = DAO.OpenDatabase(DbFile)
If Err.Number = 3024 Then MsgBox "Check connection string in the VBA StaticClass object", vbOKOnly
Because of On Error Resume Next, any error other than 3024 ("Could not find file") will pass silently and OpenConn will not be set as you intend. Later when you attempt to use OpenConn, you will trigger another error. And, in a comment, you reported you do get another error with this line:
Set runSQL = OpenConn.OpenRecordset(sql)
Unfortunately, due to On Error Resume Next, we don't know why OpenDatabase failed leaving OpenConn unset. Since ObjAccess seems to work as an Access application object, you could try setting OpenConn to ObjAccess.CurrentDb.
Private Sub Class_Initialize()
Set ObjAccess = CreateObject("Access.Application")
ObjAccess.Visible = False
ObjAccess.OpenCurrentDatabase DbFile
Set OpenConn = ObjAccess.CurrentDb
End Sub
OTOH, you may be able to dispense with OpenConn entirely if you change your runSQL function like this ...
Public Function runSQL(ByVal sql As String) As Recordset
'Set runSQL = OpenConn.OpenRecordset(sql) '
Set runSQL = ObjAccess.CurrentDb.OpenRecordset(sql)
End Function
One way to open a accdb (SQL Server) table is this:
Dim cmd As New ADODB.Command
Dim rs As ADODB.Recordset
Dim strSQL As String
strSQL = "select SomeStuff from SomeTable"
cmd.ActiveConnection = CurrentProject.Connection
cmd.CommandText = strSQL ' you can put in the SQL directly,
' but I find the string easier to manipulate away from the .CommandText
Set rs = cmd.Execute
My References (Access 2010):
I think the critical one you would need to add would be the Microsoft ActiveX Data Objects X.X Library
Imports System.Data.OleDb
Public Class Form1
Dim strSQL As String
Dim ds As New DataSet
Dim strConnection As String
Dim DBconnection As New OleDbConnection
Dim oledbAdapter As New OleDbDataAdapter
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
strConnection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=P:\Informatica\April - Juni\Acces\db-games.accdb"
DBconnection = New OleDbConnection(strConnection)
strSQL = "SELECT * from tbl_games"
Try
DBconnection.Open()
oledbAdapter = New OleDbDataAdapter(strSQL, DBconnection)
oledbAdapter.Fill(ds)
DataGridView1.DataSource = ds.Tables(0)
Catch ex As Exception
MsgBox(ex.ToString)
End Try
DBconnection.Close()
End Sub
End Class
Dim con As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=P:\Informatica\Acces\db_Games.accdb;Persist Security Info=False")
Dim cmd As New OleDbCommand
con.Open()
cmd.Connection = con
cmd.CommandText = "INSERT INTO tbl_gerne(Omschrijving) VALUES('adventure')"
cmd.ExecuteNonQuery()
con.Close()