How to connect to odcb database with excel vbs - excel

thx to google I figured out a lot of weird tricks you can do to connect to simple SQL server or SAP database and such. However, no matter how hard I try I can not create odbc object.
I can pull odbc database to excel, but this is not what I want to do.
I want to use INSERT and DELETE SQL queries.
The simplest line of codes I found were these:
Private Sub ConnectDB()
Dim oConn As ADODB.Connection
Set oConn = New ADODB.Connection
oConn.Open "DRIVER={MySQL ODBC 5.1 Driver};" & "SERVER=******.****.**;" & "DATABASE=testServer;" & "USER=Mikk;" & "PASSWORD=**;" & "Option=3"
End Sub
I have ticked the box for ActiveX data object 2.8 Library
I get run-time error '-2147467259 (80004005)
Automation error
Unspecified error

Money solves problems :)
I didn't use the correct database name and did not use DSN.
Also using a specific driver was not a good idea.
Even the server aadress was not needed.
Here is the solution:
Sub test_connection()
Dim oConn As New ADODB.Connection
Dim strUsername As String
Dim strPassword As String
Dim strDatabase As String
strUsername = "Mikk"
strPassword = "****"
strDatabase = "test"
oConn.Open "DSN=testServer;" & _
"Database=" & strDatabase & ";" & _
"Uid=" & strUsername & ";" & _
"Pwd=" & strPassword
oConn.Close
Set oConn = Nothing
End Sub

Related

Update Excel worksheet using ADODB from external application

I've found lots of posts on this problem, but so far no solutions have helped.
I'd like to read and write data from/to an Excel worksheet from an external VBA application - so far it reads OK, but I get an error while trying to write values to the ADODB Recordset.
Here's the code:
Sub UpdateFromExcel()
'https://stackoverflow.com/questions/15620080/reading-data-using-oledb-from-opened-excel-file
Dim oConn As New ADODB.Connection
Dim oRS As New ADODB.Recordset
Dim sPath
Dim sSQL As String
sSQL = "SELECT * FROM [Sheet1$A1:N10000]"
sPath = frmExcelSync.txtFilePath
oConn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" & sPath & "';" & _
"Extended Properties='Excel 12.0;HDR=Yes;IMEX=1';"
oRS.Open sSQL, oConn, adOpenDynamic, adLockOptimistic
Do While Not oRS.EOF
'ITERATE THROUGH EACH ROW HERE
'ADD CODE ABOVE
'****GET AN ERROR HERE:****
oRS.Update "Occurrence Name", "Test"
oRS.MoveNext
Loop
oRS.Close
oConn.Close
End Sub
The error is
"Cannot update. Database or object is read-only".
I've tried different lock and cursor types, and I've tried editing the fields then using the .update method, but nothing has worked so far.
Any suggestions?
your update statement is not correct. I believe you want to update the column "Occurrence Name" with the value "Test"
What you should write is.
Do While Not oRS.EOF
oRS![Occurrence Name].value = "Test"
oRS.MoveNext
Loop
oRS.Update
The problem seems to have gone away somehow.
I tried a few different things (different spreadsheets) with mixed success then restarted the application - now it works.
No code changes at all.

ADO Connection conflicting with other excels (very weird issue)

I created quite a comprehensive End User application in VBA excel the last two months which automated the whole reporting chain based on a daily dump of data in an excel sheet.
All worked fine until the tool went live. When launching my code on a operation desk, sometime the queries on the data dump returns no results.
This only happens when the tool was not opened as a first excel instance.
So, when another excel tool is open first, my tool:
- Returns no results
- An another instance of my tool is opened in read-only
This happens as well on windows 2007 & 2010 and on Win XP & Windows 7.
It opens the other excel on following line (where the issue is situated:
'adoConn.Open sConnString'
Below my code:
Public Function createConnection() As ADODB.Connection
Dim DbPath As String
Dim sConnString As String
Dim adoConn As New ADODB.Connection
DbPath = ThisWorkbook.FullName
'Define connection String
'http://www.codeguru.com/csharp/.net/net_asp/tutorials/article.php/c19307/Whats-in-an-ADO-Connection-String.htm
sConnString = "Provider=MSDASQL.1;DSN=Excel Files;DBQ=" & DbPath & ";HDR=Yes';"
'Open the connection
adoConn.Open sConnString
'Return the connection
Set createConnection = adoConn
End Function
The connection string you're using isn't the standard Excel connection string for ADO. Replace:
sConnString = "Provider=MSDASQL.1;DSN=Excel Files;DBQ=" & DbPath & ";HDR=Yes';"
adoConn.Open sConnString
with the following:
With adoConn
.Provider = "Microsoft.ACE.OLEDB.12.0"
.ConnectionString = "Data Source=" & dbPath & ";" & _
"Extended Properties=""Excel 12.0 Macro;HDR=Yes;IMEX=1"";"
.Open
End With
I rarely have issues with querying open workbooks with ADO (apart from occasional phantom read-only copies appearing)

ADODB connection to .mdb file from excel 2013

I hope someone can help.
I've developed an excel package that updates a .mdb access database through the connection string "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\"
The database is shared.
I have a Mitel telephony system that checks the database every 10 seconds or so to check for a new entry.
The database is updated with
Dim q As New ADODB.Command
Dim cn As New ADODB.Connection
Dim SQL As String
SQL = "INSERT INTO tbl1LinkAuths (DateTimeAdded, DateEntered, AddedBy, REG, OrderNo,AccountNumber, CentreNumber, EmailAddress, Callback, "
SQL = SQL & "MakeText, "...............
cn.Open cnDB
q.ActiveConnection = cn
q.CommandText = SQL
'Excecute the above SQL to insert the new job record
q.Execute
Set rs = Nothing
Set cn = Nothing
Dim db As Access.Application
Set db = New Access.Application
db.Application.Visible = False
db.OpenCurrentDatabase "\\kffcis02\VWM Share\TelephonyDB.mdb", False
db.CloseCurrentDatabase
The INSERT statement updates the database fine, but I find I have to open and close the database to get it to update in time.
This package is used heavily by around 5 people at a time, making about 2 entries per minute.
It comes up with the error "file already in use", especially when using excel 2013, a lot of the time. I think this is because I have to open/close the database every time I update.
Does anybody know of a different way I can get the database to update quicker?
I've got the actual database setting to update ADODB every second and the database is shared.
I'm now desperate, as this package has went live. I didn't have any problems during testing because there wasn't as many people using it and none of them were on office 2013.
Wrong driver: Assuming a reference to activex data objects...
dim conn as adodb.connection 'module level variable
const DBNAME = "your name here"
const DBLOC = "Your dir here"
Sub UpdateDb()
dim sql as string
openconnectionroutine
sql = "INSERT INTO tbl1LinkAuths (DateTimeAdded, DateEntered, AddedBy, "
'etc
'if you want to check it worked : otherwise ditch numrecs
dim numrecs as long
conn.execute sql, numrecs
msgbox "You added " & numrecs & " records",vbokonly,"Done"
end sub
sub Openconnectionroutine()
if conn is nothing then set conn = new adodb.connection
if conn.connectionstring = "" then
conn.ConnectionString = "Driver={Microsoft Access Driver (*.mdb)};" & _
"Dbq=" & DBNAME & ";" & _
"DefaultDir=" & DBLOC & ";" & _
"Uid=Admin;Pwd=;"
end if
if conn.state = adstateopen then
else
conn.Open
end if
End sub

Unspecified run time error while executing vba script

I am new to vba and I am using vba script to connect to database from excel and get the records. I have written the following script for that.I am getting a run time error '-2147467259(80004005)':Unspecified error.
How to resolve this error. See the error screen shot.
Sub Ora_Connection()
Dim con As ADODB.Connection
Dim rs As ADODB.Recordset
Dim query As String
Set con = New ADODB.Connection
Set rs = New ADODB.Recordset
'--- Replace below highlighted names with the corresponding values
strCon = "Driver={Microsoft ODBC for Oracle}; " & _
"CONNECTSTRING=(DESCRIPTION=" & _
"(ADDRESS=(PROTOCOL=TCP)" & _
"(HOST=host_name)(PORT=1521))" & _
"(CONNECT_DATA=(SERVICE_NAME=service_name))); uid=id; pwd=pw;"
'--- Open the above connection string.
con.Open (strCon)
'--- Now connection is open and you can use queries to execute them.
'--- It will be open till you close the connection
query = "select * from security.forms"
Set rs = con.Execute(query)
For i = 0 To rs.Fields.Count - 1
Sheet1.Cells(1, i + 1).Value = rs.Fields(i).Value
Next
con.Close
End Sub
Error screen shot:
Had you tried to use the open method of your RecordSet instance? Maybe it will give you another error that will be more helpful.
Dim connection As New ADODB.connection
Dim rst As New ADODB.Recordset
Dim query As String
connection.ConnectionString = CONNECTION_STRING
connection.Open
rst.Open query, connection, adOpenKeyset, adLockOptimistic
do while not rst.EOF
rst.MoveNext
loop
connection.Close
I had the exact same problem and it was tough to find an answer since most posts on this issue are unanswered.
I solved it by using another Oracle driver. Instead of Microsoft ODBC for Oracle try using the Oracle in OraClient11g_home1 driver. Hope this helps
Please add the reference 'Microsoft ActiveX Data Objects 2.8 Library'

Problem updating record in Access 2007 database from Excel Worksheet

I have a macro in my excel workbook that updates a specific record in the access database related to the spreadsheet.
All works fine if the access database is closed. Problems arise if the database is open and a user is editing the specific record that the excel spreadsheet relates to.`
I get the following Error Message:
Error Number 2147467259:
The database has been paced in a state by user 'ADMIN' on
'LAPTOP' that prevents it from being opened or locked.
I have set the database form's Record Locks to 'No Record Locks' but this hasn't helped.
Any advice or help is greatly appreciated.
Cheers
Noel
Public Sub updateAccessRecord()
On Error GoTo ProcError
Dim subFuncName As String
subFuncName = "updateAccessRecord"
Dim conn As ADODB.Connection
Dim cmd As ADODB.Command
Dim rst As ADODB.Recordset
Dim dbName As String
Dim dbPath As String
Dim strCon As String
Dim recID As Long
Dim fieldVal As Double
Dim strSQL As String
fieldVal = Worksheets("House Claim").Cells(593, 10).Value
dbName = "claim-db.mdb"
dbPath = ThisWorkbook.Path & "\..\..\..\..\"
dbPath = dbPath & "\" & dbName
strSQL = "UPDATE tblInsClaimDet SET propSet=" & fieldVal & " WHERE ID=" & recID & ""
Set conn = New ADODB.Connection
With conn
.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=" & dbPath
.Open
End With
Set cmd = New ADODB.Command
With cmd
.ActiveConnection = conn
.CommandText = strSQL
End With
Set rst = cmd.Execute
Set rst = Nothing
conn.Close
Set conn = Nothing
ExitProc:
Exit Sub
ProcError:
MsgBox "Error " & Err.Number & ": " & Err.Description, _
vbCritical, "Error in procedure in " & subFuncName
Resume ExitProc
End Sub
It seems that you have not split the database into a front-end and a back-end. The problem goes away if you do. Ctrl+S is not for saving a record, that is Shift+Enter, it is for saving a database object, and so it seems it has the effect of throwing the database into design or development state.
On the macro side; have you tried opening your connection as read-only? Even though your Access user is not locking the record, he has a "read lock" on the record, thereby preventing an exclusive lock by excel. I'm thinking that if both users are only attempting only read access, you should be Ok; but if either one is doing read/write, then it will fail.
On your access form, you should also have:
Me.AllowAdditions = True
Me.AllowDeletions = False
Me.AllowEdits = False
The problem is probably not in your code. The error:
The database has been paced in a state by
Indicates that the database has been opened in an exclusive mode. You should check how you are opening the database.

Resources