Unspecified run time error while executing vba script - excel

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'

Related

How to query MS Access using Excel VBA

I have been using the following method to query an MS Access database using Excel VBA for over a decade. All of a sudden yesterday it stopped working. I tried all of the following - reboot, move files to local machine, reinstall Office, a different PC, compact repair database, new database, new excel file, updating reference library (didn't see anything newer), and I've tried several other snippets of code found online.
If i relaunch excel it will work for 1-2 queries then throws the error:
Run-time error '-2147467259 (80004005)':
Unspecified error
It breaks on the line:
con.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & AccessFile
Here is the code I am running:
Public Function getRS(sSql As String) As Variant
Dim con As ADODB.Connection, rs As ADODB.Recordset
Dim AccessFile As String
Dim Rw As Long, Col As Long, c As Long
Dim MyField, Location As Range
'specify path to db
AccessFile = dbPath 'public variable
'On Error Resume Next
'Create the ADODB connection object.
Set con = CreateObject("ADODB.connection")
'Open the connection.
con.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & AccessFile
'Create the ADODB recordset object.
Set rs = CreateObject("ADODB.Recordset")
'Set thee cursor location.
rs.CursorLocation = 3 'adUseClient on early binding
rs.CursorType = 1 'adOpenKeyset on early binding
'On Error Resume Next
'Open the recordset.
rs.Open sSql, con
Set getRSOLD = rs
Set Location = Nothing
Set con = Nothing
Set rs = Nothing
End Function

VBA - ADODB connect to remote Oracle db

I am developing an Excel VBA program that I want to connect to a remote Oracle 11g database, run a query, and return the data to Excel.
Connection strings and drivers are all OK as far as I know. (see below)
It was working perfectly for a while yesterday, connecting to db and returning with correct data. Then I saved and closed the workbook, opened it 20 minutes later (no changes made!) and when I ran the macro I got the following error:
Runtime error '-2147418113 (8000ffff)': Catastrophic failure
any ideas what could be causing the error?
Could it be something on the DB's side?
Thanks
Sub ExtractFromOracle(environment As String)
Dim cn As ADODB.connection
Dim recordSet As ADODB.recordSet
Set cn = CreateObject("ADODB.Connection")
Set recordSet = CreateObject("ADODB.recordset")
Dim SQLQuery As String
SQLQuery = "SELECT User_Id, Prof_Id FROM user_profile ORDER BY User_Id ASC"
Dim returnData As Variant
Dim returnedRowsCount As Integer
Dim connectionString As String
connectionString = ReturnConnectionString(environment)
cn.Open (connectionString) ------------> ERROR OCCURS HERE
Set recordSet = cn.Execute(SQLQuery)
returnData = Application.Transpose(recordSet.GetRows)
returnedRowsCount = UBound(returnData)
If Not SheetExist(environment) Then
CreateTab (environment)
End If
Worksheets(environment).Activate
ActiveSheet.Range("A1:B" & returnedRowsCount) = returnData
Set rs = Nothing
Set cn = Nothing
ConsolidateUsers (environment)
End Sub
CONNECTION STRING :
"Provider=OraOLEDB.Oracle;Data Source=(DESCRIPTION=(CID=GTU_APP)(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=xxxxxxx)(PORT=xxxx)))(CONNECT_DATA=(SID=xxxxx)(SERVER=DEDICATED)));User Id=xxxxxx;Password=xxxxxxx;"
Can you try to access the ADODB as below
Dim strSQL As String, conStr as String
Dim cnn As New ADODB.Connection
Dim rs As New ADODB.Recordset
conStr = "Provider=OraOLEDB.Oracle;Data Source=(DESCRIPTION=(CID=GTU_APP)(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=xxxxxxx)(PORT=xxxx)))(CONNECT_DATA=(SID=xxxxx)(SERVER=DEDICATED)));User Id=xxxxxx;Password=xxxxxxx;"
Dim SQLQuery As String
SQLQuery = "SELECT User_Id, Prof_Id FROM user_profile ORDER BY User_Id ASC"
cnn.open conStr
rs.Open SQLQuery, cnn, adOpenStatic, adLockOptimistic, adCmdText
I fixed the error so I though I would update for anyone with the same issue who finds this thread.
It turns out that the 'Catastrophic Failure' error was due to my Oracle ODBC driver (oraOLEDB.oracle) becoming somehow corrupted, I couldn't even reinstall it properly, the error only occurred on my machine.
In the end I did a system restore to a point from before the issue and all was fixed. Not the most elegant solution but it worked.

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

Trying to get data from sql server 2005 from excel macro

I am trying to get data from sql server 2005 to excel..
I have written code in excel vba
Below is my code
Dim strConnection, conn, rs, strSQL
strConnection = "Provider=sqloledb;Data Source=LEON7269-G09\SQLEXPRESS;Initial Catalog=test;User Id=sa;Password=sa#123;"
Set conn = Server.CreateObject("ADODB.Connection")
conn.Open strConnection
Set rs = Server.CreateObject("ADODB.recordset")
strSQL = "SELECT * FROM UserDetails"
rs.Open strSQL, conn, 3, 3
rs.MoveFirst
While Not rs.EOF
Response.Write (rs("myField") & "<br/>")
rs.MoveNext
Wend
rs.Close
Set rs = Nothing
conn.Close
Set conn = Nothing
But i am getting error at line
Set conn = Server.CreateObject("ADODB.Connection")
as runtime error 424
i have tried adding references in vba-->tools-->references
but nothing is working ...Please guide me
If this is Excel VBA, you should get rid of all references to server, that is:
CreateObject("ADODB.Connection")
Not
Server.CreateObject("ADODB.Connection")
This won't work, either:
Response.Write (rs("myField") & "<br/>")
One of the reason for using late binding could be:
Late binding has the advantage that you don not have to compile your code
In case of use in a vba macro, there's no need to set a reference, which make a vba macro harder to deploy
It is said that late binding perform slower because the object-interface is later assigned to the object, hence the expression late binding.
Regards.
You mentioned you have laid a reference then you should have this
Dim conn as Connection
Dim rst as Recordset
Set conn = New Connection

Clearing a table

What I'm trying to do is, while in Excel, use VBA to push data to an existing Access table. I've been able to do this, but am having one small hiccup. Before I push the data to access, I want to clear the current data on the Access table, so when the new data from Excel comes in, it is the only data in the Access table. I really don't know how to write code for Access since the class has been on VBA for Excel. I've tried several different approaches and each time it doesn't work. For example, the code that seemed like it should work is
DoCmd.RunSQL "DELETE tblName.* FROM CoversheetTableFourthAttempt
but I get an error telling me to define an object.
If you could help me with this, I would really appricate it
I've put my code below for reference.
Sub AccessFourthMonth()
Dim cn As ADODB.Connection, rs As ADODB.Recordset, r As Long
' connect to the Access database
Set cn = New ADODB.Connection
cn.Open "Provider=Microsoft.Jet.OLEDB.4.0; " & _
"Data Source=C:\Users\Kent\Documents\MBA\Winter 2009 Semester\MBA 614\Final Project\shilded\testdatabase.mdb"
' open a recordset
Set rs = New ADODB.Recordset
rs.Open "CoversheetTableFourthAttempt", cn, adOpenKeyset, adLockOptimistic, adCmdTable
' all records in a table
r = 2 ' the start row in the worksheet
Do While Len(Range("A" & r).Formula) > 0
' repeat until first empty cell in column A
With rs
.AddNew ' create a new record
' add values to each field in the record
.Fields("Project") = Range("A" & r).Value
.Fields("Description") = Range("B" & r).Value
.Fields("Amount") = Range("C" & r).Value
.Fields("Date") = Range("D" & r).Value
.Update ' stores the new record
End With
r = r + 1 ' next row
Loop
rs.Close
Set rs = Nothing
cn.Close
Set cn = Nothing
End Sub
Try
DoCmd.RunSQL "DELETE * FROM TableName"
This article might be of interest: Executing SQL Statements in VBA Code
Try the following from Excel:
dim cn as adodb.connection
dim cmd as adodb.command
set cn = new adodb.connection
cn.open "put your connection string here"
set cmd = new adodb.command
cmd.commandtype = adcmdtext
cmd.commandtext = "Delete * from myTable"
cmd.activeconnection = cn.connectionstring
cmd.execute
DoCmd is internal to Access application and not recognized by Excel application.
Simple approach to your problem is to fire the delete query from Excel itself.
Add this part after your cn.Open "Provider.. line
cn.Execute "DELETE * FROM CoversheetTableFourthAttempt"
This should clear the table before next part which fills the data runs.
Your DoCmd approach has two problems. You used a quote to start a string, but didn't include a closing quote. But even with proper quoting, your DoCmd won't work because Excel does not know that CoversheetTableFourthAttempt is the name of a table in an Access database.
You showed that you can successfully create an ADO connection to your Access database. So my suggestion is to use the Execute method of the connection object to execute your SQL statment:
cn.Execute "DELETE FROM CoversheetTableFourthAttempt;"
Finally, visit Problem names and reserved words in Access to understand why Date, Description, and Project are not great choices for Access field names.

Resources