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
Related
I realized today that when you connect to SQL Server data source in Excel's native connection, it doesn't allow you to enter in a specific username and password. It just asks for server name and database.
In VBA , under the assumption that I wanted to import data from a SQL Server data query into Sheet1, can you please help me understand how to write that code?
For purposes of this exercise:
SQL Server Connection INFO
Server Name: TestingS,1633
Database Name: CarSales
username: car
password: sales
The query I want to run for simplicity sake can be: "select * from table"
I have been doing some research , but am getting a bit lost. I have no problem setting up standard queries with custom SQL via ODBC, but because I need VBA, it's very tricky for me. Please help.
This is an example of MSSQL.
Sub testMSSQL()
'Reference Microsoft ActiveX data object Library 2.8 ~~
Dim cnn As ADODB.Connection
Dim strSQL As String
Dim Ws As Worksheet
Set Ws = ActiveSheet
strSQL = "select * from table"
Set cnn = New ADODB.Connection
'Set the provider property to the OLE DB Provider for ODBC.
'cnn.Provider = "MSDASQL"
'cnn.Provider = "Microsoft.ACE.OLEDB.12.0"
'cnn.Provider = "MSOLAP"
cnn.Provider = "SQLOLEDB.1" '<~~ mssql
' Open a connection using an ODBC DSN.
cnn.ConnectionString = "driver={SQL Server};" & _
"server=TestingS;uid=car;pwd=sales;database=CarSales"
Set rs = New ADODB.Recordset
rs.Open strSQL, cnn.ConnectionString, adOpenForwardOnly, adLockReadOnly, adCmdText
cnn.Open
If cnn.State = adStateOpen Then
Else
MsgBox "Not connected server"
Exit Sub
End If
If Not rs.EOF Then
With Ws
.Range("a1").CurrentRegion.ClearContents
For i = 0 To rs.Fields.Count - 1
.Cells(1, i + 1).Value = rs.Fields(i).Name
Next
.Range("a2").CopyFromRecordset rs
.Columns.AutoFit
End With
Else
MsgBox "No Data!!", vbCritical
End If
rs.Close
Set rs = Nothing
cnn.Close
Set cnn = Nothing
End Sub
So I am quite new to VBA but I need to write a VBA macro which runs the stored procedure in Microsoft SQL server and then paste this data into the excel worksheet.
So far this is the code that I have, but I am not sure how to proceed? Is there sample code or a template for this particular procedure?
Sub Connection() ' create the connection
loginstatus = True
login.Show
Password = login.password_input
user = login.UserName
Dim con As ADODB.Connection
Dim stored_procedure As String
Dim ADODBCmd As ADODB.Command
Dim rs As ADODB.Recordset
Set con = New ADODB.Connection
'provide and create connection string
Dim connectionString As String
Dim location As String 'the server
location = "MyLocation"
connectionString = "Provider=SQLOLEDB; Network Library=DBMSSOCN;Data Source=" & location & ";Command Timeout=0;Connection Timeout=0;Packet Size=4096; Initial Catalog=ukmc; User ID=" & user & "; Password=" & Password & ";"
'handle when it is not possible to log in
On Error GoTo ConnectionError
con.Open connectionString
loginstatus = False
Exit Sub
'errorhandl0
ConnectionError:
MsgBox "Not possible to log in. Have you entered the correct password?"
'recordset - the data extracted
Set ADODBCmd = New ADODB.Command
End Sub
So i think I have created the connection, but how do I tell it which stored procedure to run and then how do i paste the data into a worksheet in my excel document?
From the link
myConnection.Open
Set myCommand.ActiveConnection = myConnection
Set myRecordSet.ActiveConnection = myConnection
myCommand.CommandText = strSQL
myCommand.CommandType = adCmdText
myCommand.Execute
myRecordSet.Open myCommand
'Paste to spreadsheet
ThisWorkbook.Worksheets("Report").Range("a2").CopyFromRecordset
myRecordSet
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