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
Related
Set wb = xl.Workbooks.Open(fileName)
Set ws = wb.Sheets("Sheet1")
cn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & fileName & ";Extended Properties=""Excel 8.0;HDR=YES;IMEX=1;"";"
Set rs = db.OpenRecordset("Tracking", dbOpenTable)
ws.Cells.ClearFormats
The bug trigger according to access is
Set rs = db.OpenRecordset("Tracking", dbOpenTable)
as "Type mismatch". I have already build a table name as "Tracking" in my access application, so I was confused why it is not processed.
PS. I am trying to add new records from Excel to Access table through recordset.
Thanks in advance!
It seems that the problem does not have anything to do with Excel. In order to help somehow, there should be a way to make a MVCE, which would actually be enough for everyone to copy, paste it and replicate the error.
Something like this in Access is quite enough:
Sub TestMe()
Dim rs As Recordset
Dim db As Database: Set db = CurrentDb
Set rs = db.OpenRecordset("Tracking", dbOpenTable)
End Sub
If you still have problems with even this code, then it is a good start.
Let me start of by saying I am new to both this site as well as VBA so please bear with me. Thank you in advance for your help.
I have a VBA function that runs an existing query from Access. Some of the tables being queried are stored in an Oracle database that require a user specific password access. Right now, a sub that I wrote to automate a report calls this function 7 times and requires the user to input their Oracle password each time the function is called (it also stops the sub and gives an error message if they type in the password incorrectly which I see as a likely event if they need to do it 7 times). The code works but I would like to find a way to have the code ask for the password once and be done with it. All of the solutions I have found involve connecting to and querying Oracle directly which requires very complicated SQL coding that I am by no means capable of writing.
I am also having an issue where the columns show up in the excel sheet in a different order than they do in Access for some of the queries. This seems to be consistent so it isn't to big of a problem but I would like to know how to prevent this to prevent any future issues.
Here is the code for the function I am currently using. Any insight would be greatly appreciated!
Option Explicit
'Single Argument "qryName" as string. Runs access qry and copys recordset to active sheet.
Function AccessQueryPull(qryName As String)
'Declare variables
Dim rs As ADODB.Recordset
Dim cn As ADODB.Connection
'open the connection to the access database
Set cn = New ADODB.Connection
cn.Open "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=filePath.accdb;"
'format the command to run the query
Dim cmd As New ADODB.Command
cmd.CommandType = adCmdStoredProc
cmd.CommandText = qryName
cmd.ActiveConnection = cn
'execute the query
Set rs = New ADODB.Recordset
Set rs = cmd.Execute()
'copy data to excel sheet
ActiveSheet.Cells(2, 1).CopyFromRecordset rs
'Cleanup
rs.Close
Set rs = Nothing
The reason you are prompted each time for Oracle credentials is that you create a fresh, new connection to MS Access each time the function is called.
Simply persist the MS Access connection by connecting once in the Sub that calls function and pass connection object as parameter. In this way, any connection error is caught in the parent routine. As for column order simply declare the columns in the needed order in SQL statement.
Sub RunQueries()
Dim rs As ADODB.Recordset
Dim cn As ADODB.Connection
'open the connection to the Access database
Set cn = New ADODB.Connection
cn.Open "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=filePath.accdb;"
Call AccessQueryPull(cn, "SELECT Col1, Col2, Col3 FROM Qry1") ' AND OTHER 6 CALLS
cn.Close
Set cn = Nothing
End Sub
Function AccessQueryPull(accConn As ADODB.Connection, qryName As String)
'format the command to run the query
Dim cmd As New ADODB.Command
cmd.CommandType = adCmdStoredProc
cmd.CommandText = qryName
cmd.ActiveConnection = accConn
'execute the query
Set rs = New ADODB.Recordset
Set rs = cmd.Execute()
'copy data to excel sheet
ActiveSheet.Cells(2, 1).CopyFromRecordset rs
'Cleanup
rs.Close
Set rs = Nothing: Set cmd = Nothing
End Function
I am trying to export a worksheet to Access where it will be paste appended into an existing table. I've referenced this post, this other post, and this other post. I'm getting an error that was not addressed in any of them that I think might be related to VBA libraries but could be something completely different. Here is my code:
Sub ExcelToAccessAdo()
Dim cn As ADODB.Connection, rs As ADODB.Recordset, row As Long
Set cn = New ADODB.Connection
cn.Open "Provider=Microsoft.ACE.OLEDB.12.0; " & _
"Data Source=filepath\AccessDB.accdb;" 'this is a different filepath from the real one.
' open a recordset
Set rs = New ADODB.Recordset
rs.Open "Table Export", cn, adOpenKeyset, adLockOptimistic, adCmdTable
row = 2 ' the start row in the worksheet
Do While Not IsEmpty(Worksheets("Table Export").Range("A" & row))
With rs
.AddNew ' create a new record
.Fields("REPTNO") = Worksheets("Table Export").Range("A" & row).Value
.Update
End With
row = row + 1
Loop
rs.Close
Set rs = Nothing
cn.Close
Set cn = Nothing
End Sub
The worksheet name and Access table name are the same. Also the .Fields("REPTNO") line is straight from the other person's post so I don't know if I'll have to change it or not.
The error is Run-time error '-2147217900 (80040e14)': Syntax error in FROM clause.
on the line rs.Open "Table Export", cn, adOpenKeyset, adLockOptimistic, adCmdTable.
This is a strange error since it seems like an error I'd get when running SQL, but I'm assuming there's some background SQL happening with an INSERT INTO clause. Which maybe this is some type of file path issue with Excel? Any help?
Here are my library References:
Microsoft Excel 14.0 Object Library
OLE Automation
Microsoft Office 14.0 Object Library
Microsoft Forms 2.0 Object Library
Microsoft ActiveX Data Objects 6.1 Library
Microsoft ActiveX Data Objects Recordset 6.0 Library
Thanks to #JNevill who pointed out I just needed to use square brackets:
rs.Open "[Table Export]", cn, adOpenKeyset, adLockOptimistic, adCmdTable
Try to stay away from spaces in any object name (Tables, Field_Names, Forms, Reports, etc.). You can do this, but as you can tell, it's going to cause more time and unnecessary frustration to normalize things. Also, don't use reserved words in your code.
https://support.microsoft.com/en-us/kb/286335
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'
Using a VBA script in Excel, I'm trying to insert a new row into a table and then get back the identity value of that row. If I run:
INSERT INTO DataSheet(databaseUserID, currentTimestamp)
VALUES (1, CURRENT_TIMESTAMP);
SELECT SCOPE_IDENTITY()
in Management Studio, the row is inserted and it gives me the returned identity value as expected. However, when I run the exact same query through a ADODB recordset in VBA, I'm having trouble. The row is indeed inserted, but I can't access the identity value. The recordset lists 0 fields and has actually been closed as well. I've tried with and without the semicolon, and I also tried running the query as a single transaction as well. Same deal, no dice. Any idea what is going on?
Here's my VBA:
Dim rs As ADODB.Recordset
Dim cn As Connection
Dim SQLStr As String
Dim serverName As String
Dim databaseName As String
serverName = "MSSQLServer"
databaseName = "QA"
cxnStr = "Driver={SQL Server};Server=" & serverName & ";Database=" & databaseName & ";"
SQLStr = "INSERT INTO DataSheet(databaseUserID, currentTimestamp)
VALUES (1, CURRENT_TIMESTAMP); SELECT SCOPE_IDENTITY()"
Set cn = New ADODB.Connection
cn.Open cxnStr
Set rs = New ADODB.Recordset
rs.Open SQLStr, cn, adOpenKeyset, adLockOptimistic
MsgBox (rs.Fields(0).Value)
And the message box fails to display because the rs.Fields(0).Value returns NULL. I added a watch to rs, and, like I said, shows 0 fields after the query and also appears to be closed (state = 0).
When you run a batch of commands using ADODB, I believe it runs each one seperately. To force the next command to run, you have to use the following:
Set rs = rs.NextRecordset()
Changing the end of your routine to the following should do the trick:
Set rs = New ADODB.Recordset
rs.Open SQLStr, cn, adOpenKeyset, adLockOptimistic
Set rs = rs.NextRecordset
MsgBox (rs.Fields(0).Value)
You are executing two statements so you will get two results back. the recordset object can only hold one result at a time - to get the other result you need to use the NextRecordset method.
Set rs = rs.NextRecordset
In your rs.Open Try this
rs.Open SQLStr, cn, adCmdText
See what happens when you remove the adOpenKeySet and adLockOptimistic values leave them at their defaults.