Connect Excel to Access - VBA - vba

I get a "User-defined type not defined" error when I execute the below code, and the
"objCon As ADODB.Connection"
is highlighted on the first line.
I am trying to set a connection from Excel to Access via VBA code. Thank you for any advice!
Private objCon As ADODB.Connection
Private rstRec As ADODB.Recordset
Private strQry
Sub Connect()
Dim strConn As String
Set objCon = New ADODB.Connection
objCon.Mode = adModeReadWrite
If objCon.State = adStateClosed Then
strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & "C:\DB\Db.accdb;Persist Security Info=False;"
objCon.ConnectionString = strConn
objCon.Open
End If
End Sub

You can do one of the following
set objCon = CreateObject("ADODB.Connection")
set rstRec = CreateObject("ADODB.Recordset")
Or in VBA Editor
Tools-->Reference-->
Add Microsoft ActiveX Data Object X.Y Library

Related

Creating persistent ADODB connection on workbook/worksheet opening

Right now I have an Excel worksheet full of hundreds (if not thousands) of functions, each one individually opening an ADODB connection to my SQL Server, executing a command, then closing the connection - this has led to some lengthy waiting periods while refreshing data.
Public Function Alere(StoredProcedure As String, paramItem As Range)
Dim conn As ADODB.Connection
Dim rs As ADODB.Recordset
connString = [connection string]
Set conn = New ADODB.Connection
Set rs = New ADODB.Recordset
conn.Open sConnString
Set rs = conn.Execute("[query]")
If Not rs.EOF Then
Alere = rs(0)
Else
Alere = "-"
End If
End Function
Would it be possible to open my connection on worksheet_activate(), and have it persist so that I can just reference it at any point? I have attempted putting the following at the top of the module:
Public conn As ADODB.Connection
Public rs As ADODB.Recordset
Set conn = New ADODB.Connection
Set rs = New ADODB.Recordset
conn.Open ("DSN=" & Worksheets("Variables").[H2] & ";Trusted_Connection=Yes;WSID=" & Environ("COMPUTERNAME") & ";DATABASE=" &
Worksheets("Variables").[H3])
...but I get issues regarding "Set" not being allowed outside of a function/sub.
So is there any way to have the connection persist and I simply continue to execute commands through it?

ADO Connection and Recordset with HTTP data source

I have the below Macro reading from a Database table stored as a txt file on the local C drive and returning an SQL query.
Public Function getData(fileName As String) As ADODB.Recordset
Dim cN As ADODB.Connection
Dim RS As ADODB.Recordset
Set cN = New ADODB.Connection
Set RS = New ADODB.Recordset
cN.Open ("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Cloud\;Persist
Security Info=False;Extended Properties=""text; HDR=Yes; FMT=Delimited;
IMEX=1;""")
RS.ActiveConnection = cN
RS.Source = "select top 10 * from " & fileName
Set getData = RS
End Function
I can then call the function and return data using the below, so far so good...
Sub Cloud()
Dim a As ADODB.Recordset
Set a = getData("file.txt")
a.Open
MsgBox (a.GetString())
a.Close
End Sub
BUT now I would like to move 'file.txt' from C:\Cloud\ to a HTTP location, ie http://it.wont.work/
How would I amend the above for this to work? I've searched and tested but nothing seems to work... I either get internet login failed or ISAM not found.
Many thanks

Connection String for MS Access Database incorrect

I am trying to extrapolate data from an MS Access 2007/2010 Database.
I have the following code in VBA but the connection string is incorrect. I have added the relevant REFERENCES libraries
Private Sub btnGetMsAccessData_Click()
Dim sConn As String
Dim oConn As ADODB.Connection
Dim oRs As ADODB.Recordset
Dim sSQL As String
sConn = "Provider=Microsoft.ACE.OLEDB.12.0;User ID=Admin;Data Source=\\MyNetworkPath\BP-MasterDashboard Source\BP_Planning_by_PT_dept_be.accdb;Mode=Read"
Set oConn = New ADODB.Connection ' Open a connection.
oConn.Open
sSQL = "SELECT * FROM Tbl_Start_Leaver" ' Make a query over the connection.
Set oRs = New ADODB.Recordset
oRs.Open sSQL, , adOpenStatic, adLockBatchOptimistic, adCmdText
MsgBox oRs.RecordCount
oConn.Close ' Close the connection.
Set oConn = Nothing
End Sub
It fails saying Unknown Application error on the oConn.Open line.
I have tried to link a Workbook to one of the tables and this works fine.
I then looked at the "Connection" and copied it into my code but still no joy.
Keeps saying :
Automation Error
Unexpected Error
Any ideas would be appreciated.
Thanks in advance.
While the connection string was incorrect, there were other issues as well. Such as, not assigning the connection String to the ADODB Connection object as well as others. Here is the updated code that I hope will get you operational
Private Sub btnGetMsAccessData_Click()
'Ensure you add a reference to Microsoft ADO Objects
Dim oConn As New ADODB.Connection
Dim oRs As New ADODB.Recordset
Dim sSQL As String: sSQL = "SELECT * FROM Tbl_Start_Leaver"
'Corrected Connection String from Thomas Inzina
Dim sConn As String: sConn = "Provider=Microsoft.ACE.OLEDB.12.0;UID=Admin;Data Source=" & _
"\\MyNetworkPath\BP-MasterDashboard Source\BP_Planning_by_PT_dept_be.accdb;Mode=Read"
With oConn
.ConnectionString = sConn ' You need to assign the connection string to the ADODB.Connection Object
.Open
End With
'Make sure the connection isn't open before opening the recordset
'You also need to specify which connection you want to use as the second parameter (this was missed)
If oRs.State <> adStateOpen Then oRs.Open sSQL, oConn, adOpenStatic, adLockBatchOptimistic, adCmdText
'Close Connection and RS
If oConn.State = adStateOpen Then oConn.Close
If oRs.State = adStateOpen Then oRs.Close
'Clean Up
Set oRs = Nothing
Set oConn = Nothing
End Sub

How to Lock Only the Current ADODB.Recordset Instead of the Whole Page (or Table) in VBA/Access

I want to lock just the current ADODB recordset (but not the page or the entire table) of a multi-user system developed in VBA/Access so that any other user that opens the same recordset cannot edit one recordset position already in edit mode in some other user computer. I want to avoid 2 o more users editing the same record position (eg: more than one user editing the registration of the same employee).
I tested the folowing code, unsuccessfully:
Private Sub Form_Load()
Dim dbcon As ADODB.Connection
Dim recrdst As ADODB.Recordset
Set recrdst = New ADODB.Recordset
recrdst.CursorType = adOpenKeyset
recrdst.LockType = adLockPessimistic
Set dbcon = New ADODB.Connection
dbcon.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=C:\Família\Alex Borges\Companies\Imobiliária Halex Tiago\Estudos\Sistema Multi-Usuário\Servidor.mdb;"
recrdst.Open "SELECT * FROM tblDependentes", dbcon
Set Me.Recordset = recrdst
Set recrdst = Nothing
Set dbcon = Nothing
End Sub
I also tested the folowing code:
Private Sub Form_Load()
Dim dbcon As ADODB.Connection
Dim recrdst As ADODB.Recordset
Set dbcon = New ADODB.Connection
dbcon.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=C:\Família\Alex Borges\Companies\Imobiliária Halex Tiago\Estudos\Sistema Multi-Usuário\Servidor.mdb;"
Set recrdst = New ADODB.Recordset
recrdst.ActiveConnection = dbcon
recrdst.CursorType = adOpenKeyset
recrdst.LockType = adLockPessimistic
recrdst.CursorLocation = adUseServer
recrdst.Open "SELECT * FROM tblDependentes", dbcon
Set Me.Recordset = recrdst
Set recrdst = Nothing
Set dbcon = Nothing
End Sub
my Access version is 2007. on Access/Options/Advanced, I changed the default record locking to "edited record".
thanks in advance.

runtime error '-2147217900' (80040e14)': automation error using where in the sql query from excel vba

I am trying to connect to my sqlserver express 2005 from excel vba using the following (copied from some forum routine as i am not very into databases). It works perfect. As soon as I use WHERE in the sqlquery variable (already verified quotes double and single) i get
runtime error '-2147217900' (80040e14)':
automation error
Similar routine that work pulling data from other people same thing. I appreciate deeply your help
Thanks
Sub ConnectTEST()
' Create a connection object.
Dim cnPubs As ADODB.Connection
Set cnPubs = New ADODB.Connection
Dim sqlquery As String
Dim rsPubs As ADODB.Recordset
Set rsPubs = New ADODB.Recordset
' Provide the connection string.
Dim strConn As String
'Use the SQL Server OLE DB Provider.
strConn = "PROVIDER=SQLOLEDB;"
sqlquery = "SELECT * FROM [Logisuite].[dbo].[EoWebStatus]"
'Connect to the Pubs database on the local server.
strConn = strConn & "Server=SERVITRANSMAIn\SQLEXPRESS;Database=logisuite;Trusted_Connection=True;"
'Use an integrated login.
strConn = strConn & "INTEGRATED SECURITY=sspi;"
'Now open the connection.
cnPubs.Open strConn
' Create a recordset object.
Set rsPubs = New ADODB.Recordset
With rsPubs
' Assign the Connection object.
.ActiveConnection = cnPubs
' Extract the required records.
.Open sqlquery
' Copy the records into cell A1 on Sheet1.
Sheet1.Range("A1").CopyFromRecordset rsPubs
' Tidy up
.Close
End With
cnPubs.Close
Set rsPubs = Nothing
Set cnPubs = Nothing
End Sub