I'm using Excel 2010 VBA to retrieve data from MS Access 2010 with ODBC connection to SQL Server R2 Express, in my previous machine there is no issue (32bit platform) but when I got new machine it's always said "ODBC connection to (odbc name) failed -2147467259".
From Access 2010 to SQL there is no issue, but when I retrieve data from Excel always trigger this error.
I have check the permission for the user (DBO), all the app in the same machine, all the services are on, ODBC setting is correct. During the execution of the script all OK except when the line is opening the table.
Function RetrieveProjectList()
Dim strConn As String
Dim conn As New ADODB.Connection
Dim rec As New ADODB.Recordset
Dim intColCount As Integer
Dim strName As String
Dim strSQL As String
On Error GoTo Error_Trap
strName = ThisWorkbook.path & "\DBSource V0.1.accdb"
Set conn = New ADODB.Connection
strConn = "Provider=microsoft.ACE.oledb.12.0;"
strConn = strConn & "Data Source=" & strName & ";"
conn.Open ConnectionString:=strConn
Set rec = New ADODB.Recordset
strSQL = "SELECT qryProjectList.* " & _
"FROM qryProjectList ORDER BY tblArea.AreaName,tblProject.ProjectName;"
rec.Open strSQL, conn, adOpenDynamic, adLockOptimistic
'Retrieve data from Access
rec.MoveFirst
If rec.Fields.count <> 0 Then
After syntax "rec.open ...." the error pop up.
In other machince are OK.
Question:
Is this related to OS version 64bit? What did I miss out here?
Any advice will be highly appreciated.
Thanks, seageath
Related
I try to use again a code who whas successful on the past to bind a recordset from sql server to an Access Form.
Dim serverAddress As String, DB As String, stADO As String
serverAddress = "xxx"
DB = "yyy"
stADO = "Provider=MSOLEDBSQL;Server=" & serverAddress & ";Database=" & DB & ";UID=admin;PWD=password;"
Dim cn As New ADODB.Connection, rs As New ADODB.Recordset
cn.ConnectionString = stADO
cn.Open
rs.CursorLocation = adUseClient
rs.Open "SELECT * FROM Table", cn, adOpenStatic, adLockReadOnly
DoCmd.OpenForm "Form_Name", acFormDS
'sanity check if we have data on the Recordset
Debug.Print rs(2)
Set Forms("Form_Name").Form.Recordset = rs
cn.Close
Set cn = Nothing
For sure the recorset is populate as debug.print rs(2) return a value.
When the command : "Set Forms("Form_Name").Form.Recordset = rs" is executed the database crashed and closed.
I have added also error management with on error goto but the DB crash without any message.
Thanks in advance for any help you could provide to resolve this issue.
Alexis
Error management without success
Use alternative connexion string
Test if the recordset is populated
I recently tried to run my functioning MSAccess Database on a virtual cloud based machine running Windows Server 2019. All of my save functions do not work from the PC when editing a record. They work fine to create new records in the associated SQL tables. Below is an example of one of my save functions. Loading and creating new records works fine, just editing current SQL records causes the error
[Microsoft][ODBC Driver 17 for SQL Server] COUNT field incorrect or syntax error
Private Function fSave() As Boolean 'True if Saved properly False on Error
Dim SQLConnectionString As String
Dim SQLConnectionUserName As String
Dim SQLConnectionPassword As String
SQLConnectionString = Forms!frm00SystemSettings!txtSQLConnectionString
SQLConnectionUserName = Forms!frm00SystemSettings!txtSQLConnectionUserName
SQLConnectionPassword = Forms!frm00SystemSettings!txtSQLConnectionPassword
Dim cnn As ADODB.Connection
Dim rst As ADODB.Recordset
Dim strSQL As String
Set cnn = New ADODB.Connection
Set rst = New ADODB.Recordset
cnn.Open SQLConnectionString, SQLConnectionUserName, SQLConnectionPassword
If IsNothing(Me.txtIdentifier.Value) Then
strSQL = "SELECT * " & _
"FROM vwM01Commodity " & _
"WHERE CommodityID = Null"
Else
strSQL = "SELECT * " & _
"FROM vwM01Commodity " & _
"WHERE CommodityID = " & Me.txtIdentifier.Value
End If
rst.LockType = adLockOptimistic
rst.Open strSQL, cnn
If rst.EOF Then
rst.AddNew
End If
rst.Fields("Commodity") = Me.txtCommodity.Value
rst.Update
End Function
I am using this syntax to run a SQL Server 2008 stored procedure from Excel 2013. Everything executes as it should on one PC, but if I attempt to run it on a second PC it errors out with an
OLEDB Connection error
Shouldn't since I am hardcoding the servername, username, and password the syntax run w/o a hitch on any PC?
Function RunSQLServerProc()
Dim con As ADODB.Connection
Dim cmd As ADODB.Command
Dim rs As ADODB.Recordset
Set con = New ADODB.Connection
Set cmd = New ADODB.Command
Set rs = New ADODB.Recordset
con.Open "Provider=SQLOLEDB;Data Source=Server;Initial Catalog=Database;User Id=userid;Password=password;Integrated Security=SSPI;Trusted_Connection=Yes;"
cmd.ActiveConnection = con
cmd.CommandText = "TestProc"
Set rs = cmd.Execute(, , adCmdStoredProc)
End Function
There are two ways to connect to SQL Server through VBA
1) Integrated Security=SSPI;
2) Provide a valid username & password through the VBA
When you use SSPI, the windows login credentials of the logged in user (i.e. of the Excel workbook) will be used.
Now for you, since you are not wanting to use windows credentials you need to provide a SQL server logon with the User ID and password you specify, and that must also be associated with an account in the database with the privileges that you need.
These two samples work perfectly fine for me.
Option Explicit
Sub CallSprocOne()
Dim con As Connection
Dim rst As Recordset
Dim strConn As String
Set con = New Connection
strConn = "Provider=SQLOLEDB;"
strConn = strConn & "Data Source=LAPTOP\SQL_EXPRESS;"
strConn = strConn & "Initial Catalog=Northwind;"
strConn = strConn & "Integrated Security=SSPI;"
con.Open strConn
'Put a country name in Cell E1
Set rst = con.Execute("Exec dbo.TestNewProc '" & ActiveSheet.Range("E1").Text & "'")
'The total count of records is returned to Cell A5
ActiveSheet.Range("A5").CopyFromRecordset rst
rst.Close
con.Close
End Sub
Sub CallSprocTwo()
Dim con As Connection
Dim rst As Recordset
Set con = New Connection
con.Open "Provider=SQLOLEDB;Data Source=LAPTOP\SQL_EXPRESS;Initial Catalog=Northwind;Integrated Security=SSPI;"
Set rst = con.Execute("Exec dbo.[Ten Most Expensive Products]")
'Results of SProc are returned to Cell A1
ActiveSheet.Range("A1").CopyFromRecordset rst
rst.Close
con.Close
End Sub
I'm a bit stuck for a while in a small project
to generate results from several
sql queries in several excel Sheets, I am trying to use SQL Server 2008 and it's the first time I code VBA
I tried this code (for a SQL single query) but I still have compilation problems
Sub New_Feuil1()
ThisWorkbook.Activate
'First clear the contents from the query
Worksheets("Feuil1").Select
Range("A2").Select
Do Until ActiveCell = ""
ActiveCell.Offset(1).Select
Loop
Range("A4", ActiveCell.Offset(-1, 3)).ClearContents
'Get reporting date
ReportingDate = ThisWorkbook.Sheets("Parameters").Range("D1")
'Format the value for use in the SQL query
ReportingDateFor = Format(ReportingDate, "yyyy-mm-dd")
Worksheets("Feuil1").Select
Range("A1").Select
Dim cnn As New ADODB.Connection
Dim rst As New ADODB.Recordset
Dim StrQuery1 As String
Dim ConnectionString As String
ConnectionString ="ODBC;" & _
"Driver={SQL Server Native Client 10.0};" & _
"Server=187.125.254.231;" & _
"Database=database;" & _
"UID=sa; PWD=pwd"
cnn.Open ConnectionString
cnn.CommandTimeout = 900
'Queries to be executed
StrQuery1 = StrQuery1 & "Select Id from Users"
rst.Open StrQuery1, cnn, adOpenForwardOnly, adLockReadOnly
rst.Close
Debug.Print "StrQuery1:"; StrQuery1
cnn.Close
ThisWorkbook.Sheets("Central Dashboard").Select
Sheets("Feuil1").Range("A2").CopyFromRecordset rst
End Sub
is there any other solution ?
it seems you are new to programming :).. before you use any variables please declare them this will help you to understand them quickly.
like:
Dim ReportingDate as Date
ReportingDate = ThisWorkbook.Sheets("Parameters").Range("D1")
Dim ReportingDateFor As String
ReportingDateFor = Format$(ReportingDate, "yyyy-mm-dd")
also check your connection string. try this connection string.
ConnectionString = "Driver={SQL Server Native Client 10.0};Server=187.125.254.231;Database=database;UID=sa; PWD=pwd"
Apart from that, looking at your code you are connecting to server, opening recordset, closing recordset and finally closing the connection AND THEN trying to retrieve the results. logically this will never work :) :)
try this:
Dim cnn As New ADODB.Connection
Dim rst As New ADODB.Recordset
Dim cmd As ADODB.Command
Dim ConnectionString As String
ConnectionString = "Driver={SQL Server Native Client 10.0};Server=187.125.254.231;Database=database;UID=sa; PWD=pwd"
cnn.Open ConnectionString
'Queries to be executed
Dim StrQuery1 As String
StrQuery1 = StrQuery1 & "Select Id from Users"
'Prepare SQL execution
cmd.Name = "SelectUsers"
cmd.ActiveConnection = conn
cmd.CommandText = StrQuery1
Set rst = cmd.Execute
If Not rst.EOF Then
With Sheets(1).Cells ' Enter your sheet name and range here
.ClearContents ' clears the entire sheet
.CopyFromRecordset rst ' copy the result
End With
Else
MsgBox "no records found.."
End If
'After work done close connection
On Error Resume Next
rst.Close
cnn.Close
Set rst = Nothing
Set cnn = Nothing
We are working on changing an existing excel form to deliver a record to our SLQ server.
We have been scuccessful with code that scrubs captures and writes the data to the server using a DSN and ODBC.
scn = dsn=ODBC123
Our target users (of wich there are many) are using excel 2003 and an ODBC connection on each terminal is not practical.
This is my first venture into using ADODB.
I was tripping my badSQL message but do not get an error from the server, until I added the UID and Pass.
Now I am getting
Run-time error '-2147467559(80004005)':
Automation error
Unspecified Error
Would one of you fine ladies and/or gentlemen take a look and provide some guidence?
Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim ssql As String
Set cn = New ADODB.Connection
Set rs = New ADODB.Recordset
Const scn As String = "Provider=SQLOLEDB.1;Integrated Security=SSPI;" & _
"Persist Security Info=False;" & _
"Initial Catalog="DB on Server";" & _
"Data Source="Server Name" & _
"User ID=Form;Password=nope;"
ssql = "sql statment that writes a record to a table using info in the excel form," & _
" writen in vb that has worked through an odbc"
With cn
.CursorLocation = adUseClient
.Open scn
.CommandTimeout = 0
Set rst = .Execute(ssql)
End With
On Error GoTo badsql:
rs.Open ssql, cn, adOpenStatic, adLockOptimistic
On Error GoTo badsql:
rs.Close
cn.Close
Set rs = Nothing
Set cn = Nothing
MsgBox ("This record was updated in the database and documented for" & _
" processing. Please close this workbook.")
badsql:
MsgBox ("This record was not processed please resubmit.")
Exit Sub'
We seem to have both rst and rs as Recordset objects. I don't see a declaration for rst in the supplied code.
In any case, the query string in ssql is run twice. Once when it gets executed and the results (if any) returned into rst. The other time when rs is opened.
You probably only want to run the query string once and, as it seems to be an INSERT-type query, you probably want to use cn.Execute rather than rs.Open