VBA connecting to SQL Server - sql-server

I am having trouble when connecting VBA to SQL Server:
Sub ConnectSQLServer()
Dim cmd As ADODB.Command
Dim conn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim strConn As String
Dim par As ADODB.Parameter
Dim strSQL As String
strConn = "DRIVER=SQL Server;SERVER=CHU-AS-0004;DATABASE=RTC_LaplaceD_DEV;Trusted_Connection=Yes;"
Set conn = New ADODB.Connection
conn.Open strConn
Set cmd = New ADODB.Command
cmd.CommandText = "dbo.Version"
cmd.CommandType = adCmdStoredProc
cmd.ActiveConnection = conn
rs.Open = "SELECT * FROM [dbo].[Version]"
cmd.Execute rs
Set conn = Nothing
Set cmd = Nothing
sConnString = ""
End Sub
I just want to select all values from the table named [dbo].[Version], but when I execute it, I get an error:
Compile error: Expected Function or Variable'
and the line with rs.Open is highlighted.
Would you help me to solve this problem?

Open is a method, and cannot be set with an =.
You probably want something like this:
rs.Open "SELECT * FROM [dbo].[Version]", conn
Once you have called Open, then you can iterate through the Recordset's rows using the EOF property and the MoveNext method:
Do While Not rs.EOF
Debug.Print rs.Fields(1)
'You could also use rs!FieldName, where FieldName is the name of a column
Loop

Change your code to the following:
Set cmd = New ADODB.Command
cmd.CommandText = "SELECT * FROM [dbo].[Version]"
cmd.CommandType = adCmdText
cmd.ActiveConnection = conn
Set rs = cmd.Execute
Do While Not rs.EOF
'do something with rs.Fields(0) '
rs.MoveNext
Loop
Set conn = Nothing
Set cmd = Nothing
rs.Fields is a zero based collection that means that the first field is 0, not 1.
You can get subsequent fields by rs.Fields(1), rs.Fields(2) etc. Or you can use Field names, with the syntax rs.Fields("MyFieldName").
Note when using a string command ("SELECT * FROM ..") the CommandType is adCmdText. The syntax for the Recordset is SET rs = cmd.Execute. Also you must invoke MoveNext in your loop, otherwise you get stuck in the loop!

Related

Can't execute SQL Server stored procedure in Access module

In Access I created a form with Text1, List1, and Command1 elements.
The code for command button is:
Private Sub Command1_Click()
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=192.168.100.41,1433;Network Library=DBMSSOCN;Initial Catalog=xxx;User ID=xxx;Password=xxx;"
cmd.ActiveConnection = con
cmd.CommandTimeout = 0
cmd.Parameters.Append cmd.CreateParameter("#keyword", adVarChar, adParamInput, 100, Trim(Text1.Value))
cmd.CommandText = "stored_procedure"
Set rs = cmd.Execute(, , adCmdStoredProc)
If (rs.RecordCount <> 0) Then
Do While Not rs.EOF
Me.List1.AddItem (rs.Fields(0).Value & " | " & rs.Fields(1).Value & " | " & rs.Fields(2).Value)
rs.MoveNext
Loop
End If
rs.Close
Set rs = Nothing
Set cmd = Nothing
con.Close
Set con = Nothing
End Sub
When I try to run the code, nothing happens. No error. Seems like button is empty.
The SP works fine in SQL server.
The same button code, works fine in Excel form.
If I replace SP part with [rs.open "select * from table where keyword like.."] works fine
Thank you
You probably need to use a client side cursor, I would debug.print rs.RecordCount to check what it thinks are the returned records.
conn.cursorlocation=aduseclient

Error: "Command text was not set for the command object" when running a Stored Procedure from SQL on VBA

I'm trying to run a stored procedure on VBA using the following VBA code:
Please can someone advise: I get the error at "rs.Open".
Sub connection()
Dim Conn As ADODB.connection
Dim ADODBCmd As ADODB.Command
Dim rs As ADODB.Recordset
Dim i As Integer
Dim constring As String
Dim location As String 'the server
Dim password As String
location = "10.103.98.18"
password = "password"
constring = "Provider=SQLOLEDB; Network Library=DBMSSOCN;Data Source=" & location & ";Command Timeout=0;Connection Timeout=0;Packet Size=4096; Initial Catalog=ElColibri; User ID=Analyst1; Password=password;"
Set Conn = New ADODB.connection
Conn.connectionString = constring
'On Error GoTo ConnectionError
Conn.Open
'loginstatus = False
'Exit Sub
'errorhandl0
'ConnectionError:
'MsgBox "Not possible to log in. Have you entered the correct password?"
'open recordset
Set ADODBCmd = New ADODB.Command
ADODBCmd.ActiveConnection = Conn
ADODBCmd.CommandTimeout = 1200
ADODBCmd.CommandText = ["ukrmc.dbo.FridayCommentary"]
ADODBCmd.CommandType = 4 'adCmdStoredProc
ADODBCmd.Execute
Set rs = New ADODB.Recordset
rs.ActiveConnection = Conn
rs.Open
Conn.Close
Set Conn = Nothing
Set ADODBCmd = Nothing
'Paste to spreadsheet
ThisWorkbook.Worksheets("macrotest").Range("a2").CopyFromRecordset
'Set rs = conn.Execute(Query)
rs.Close
Set rs = Nothing
End Sub
To me the code makes logical sense to me so I am not sure what the error means. Because to me, I have set text for the command object.
You are not connecting the recordset to your command. Assuming that your stored procedure issues a SELECT, change your code to
Set rs = ADODBCmd.Execute
thisWorkbook.Worksheets("macrotest").Range("a2").CopyFromRecordset rs
The Execute-Method will return a Recordset as result, no need to create one by yourself.
Or you should add the command object to the open operation
rs.Open ADODBCmd

vba insert existing table to a new table

I am trying to insert table to new table.
This is my code and I am not sure how to proceed.
It is not a complete code.
Private Sub CommandSubmit_Click()
Dim cmd As ADODB.Command
Dim conn As ADODB.Connection
Dim strConn As String
Dim par As ADODB.Parameter 'input
strConn = "DRIVER=SQL Server;SERVER=CHU-AS-0004;DATABASE=RTC_LaplaceD_DEV;Trusted_Connection=Yes;"
Set conn = New ADODB.Connection
conn.Open strConn 'open connection
Set cmd = New ADODB.Command
cmd.CommandText = "dbo.SubmitBlend"
cmd.CommandType = adCmdStoredProc
cmd.ActiveConnection = conn
Dim strBlend As String
strBlend = "INSERT INTO dbo.SubmitBlend SELECT * FROM dbo.AddBlendPrac"
cmd.Execute
conn.Close
Set conn = Nothing
Set cmd = Nothing
MsgBox "Request Submit Succeed"
I have create a table first, and this table has data. This table needs to be inserted to a new table. Is there any one how to code this one? Any comments would be greatly helpful :)

Cannot connect to sql server with VBA (Run-time error (80040e14))

I am trying to connect to my Sql database and get one simple recordset out of it running this code:
Sub ConnectToSQL()
Dim cnn As New ADODB.Connection
Dim cmd As New ADODB.Command
Dim rs As New ADODB.Recordset
With cnn
.ConnectionString = "File Name=C:\inetpub\tc\TEST.udl"
.Open
End With
With cmd
.ActiveConnection = cnn
.CommandType = xlCmdSql
.CommandText = "SELECT * FROM TEST"
End With
rs.Open cmd.Execute, cnn
If Not rs.EOF Then
Sheets(1).Range("A1").CopyFromRecordset rs
rs.Close
Else
MsgBox "No records returned", vbCritical
End If
cn.Close
Set cn = Nothing
Set rs = Nothing
End Sub
As a result I get the run-time error message (80040e14) What could be wrong here?
Thanks,
Do you want to try following? Please do not forget to add Tools> Refernces if necessary.
Sub ConnectToSQL()
Dim cnn As ADODB.Connection
Dim rs As New ADODB.Recordset
Dim ConnectionString As String
Set cnn = New ADODB.Connection
ConnectionString = "File Name=C:\inetpub\tc\TEST.udl"
cnn.Open ConnectionString
cnn.CommandTimeout = 900
strquery = "SELECT * FROM TEST;"
'MsgBox strquery
rs.Open strquery, cnn
If Not rs.EOF Then
Sheets(1).Range("A1").CopyFromRecordset rs
rs.Close
Else
MsgBox "No records returned", vbCritical
End If
cnn.Close
Set cnn = Nothing
Set rs = Nothing
End Sub

Execute SQL Server stored procedure through VBA which does not return rows

How to execute special SQL Server stored procedure through Excel VBA? Special because it does not return rows like this procedure:
select * from tab1
How to execute the procedure which let's say prepares reports, like this one:
select *
into tab2
from tab1
which does not return any rows.
I am using this VBA code:
Dim cnn As Object
Set cnn = CreateObject("ADODB.Connection")
Dim cmd As Object
Set cmd = CreateObject("ADODB.Command")
Dim rs As Object
Set rs = CreateObject("ADODB.Recordset")
Dim ConnectionString As String
cnn.ConnectionString = "driver={SQL Server};server=MYSERVERNAME;Database=MYDATABASE;Trusted_Connection=yes;"
cnn.Open
Sql = "EXEC [dbo].[Procedure_make_report] 'param1'"
Set rs = cnn.Execute(Sql)
I get the error:
Runtime error 2147217900
I found a clue here:
http://www.vbforums.com/showthread.php?541498-RESOLVED-runtime-error-2147217900-(80040e14)-incorrect-syntax-error
but I do not know what action query is.
Based on comments of Rory and Tom, I leave the answer which works.
Dim cnn As Object
Set cnn = CreateObject("ADODB.Connection")
Dim cmd As Object
Set cmd = CreateObject("ADODB.Command")
cmd.CommandType = 1 ' adCmdText
cmd.CommandTimeout = 120 ' number of seconds to time out
Dim ConnectionString As String
cnn.ConnectionString = "driver={SQL Server};server=MYSERVERNAME;Database=MYDATABASE;Trusted_Connection=yes;"
cnn.Open
Dim SQL As String
SQL = "EXEC [dbo].[Procedure_make_report] 'param1'"
cnn.Open
cmd.CommandText = SQL
cmd.ActiveConnection = cnn
cmd.Execute
If Not cnn Is Nothing Then
cnn.Close
Set cnn = Nothing
End If

Resources