I have a stored procedure in SQL Server that I am trying to execute from Excel via some VBA code. However, the stored procedure has two outputs (see below).
My record set is only pulling in the first table (added 0 error messages...) whereas I want to pull in the second table.
Image here: http://i.stack.imgur.com/LxyLi.png
Here is my code, compiled from other sources I found on here:
Sub RefreshBarcodes()
Dim Database As String
Dim con As ADODB.Connection
Dim strconn As String
Dim SQLServer As String
Dim Session As String
Dim strSQLCommandOne As String
Application.ScreenUpdating = False
Worksheets("Master").Activate
Database = Worksheets("Master").Cells(5, "H").Value
SQLServer = Worksheets("Master").Cells(4, "H").Value
Session = Worksheets("Master").Cells(6, "H").Value
'Connect to Database
Set con = New ADODB.Connection
strconn = "Provider=sqloledb; Data Source=" & SQLServer & ";Initial Catalog = " & _
Database & "; INTEGRATED SECURITY=SSPI; "
con.Open strconn
'Set SQL Commands
strSQLCommandOne = "set nocount on; exec spGetSessionSourceCounts 'HNW-CLU-001-024_01_0005'"
'Open Recordset
Dim rs As ADODB.Recordset
Set rs = New ADODB.Recordset
'Execute and copy to Excel
rs.Open strSQLCommandOne, strconn
rs.MoveFirst
Worksheets("Session").Activate
Cells(1, 1).Select
ActiveCell.CopyFromRecordset rs
rs.Close
Worksheets("Master").Activate
Cells(6, "H").Value = "Session updated"
con.Close
Application.ScreenUpdating = True
End Sub
Excel output: http://i.stack.imgur.com/b7i3B.png
I would love to be able to pull in the first (error message) and second results (session info), but mainly need only the second table. Thanks so much in advance!
To access the second recordset, you need to execute this line:-
'Activate the next available recordset
Set rs = rs.NextRecordset
If Not rs Is Nothing Then
'Add code in here
End If
Related
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
The original question was presented in 2015. I was wanting to know if any one here is aware if a new vba code has been generated since then to string 1000+ rows?
I don't want to get into server and more complex issues if I don't have to.
See original post:
Importing more than 1000 rows from Excel to SQL-server
Your assistance is appreciated.
You should be able to find a solution here.
https://www.excel-sql-server.com/excel-sql-server-import-export-using-vba.htm#Introduction
Or, consider this.
Sub Rectangle1_Click()
'TRUSTED CONNECTION
On Error GoTo errH
Dim con As New ADODB.Connection
Dim rs As New ADODB.Recordset
Dim strPath As String
Dim intImportRow As Integer
Dim strFirstName, strLastName As String
Dim server, username, password, table, database As String
With Sheets("Sheet1")
server = .TextBox1.Text
table = .TextBox4.Text
database = .TextBox5.Text
If con.State <> 1 Then
con.Open "Provider=SQLOLEDB;Data Source=" & server & ";Initial Catalog=" & database & ";Integrated Security=SSPI;"
'con.Open
End If
'this is the TRUSTED connection string
Set rs.ActiveConnection = con
'delete all records first if checkbox checked
If .CheckBox1 Then
con.Execute "delete from tbl_demo"
End If
'set first row with records to import
'you could also just loop thru a range if you want.
intImportRow = 10
Do Until .Cells(intImportRow, 1) = ""
strFirstName = .Cells(intImportRow, 1)
strLastName = .Cells(intImportRow, 2)
'insert row into database
con.Execute "insert into tbl_demo (firstname, lastname) values ('" & strFirstName & "', '" & strLastName & "')"
intImportRow = intImportRow + 1
Loop
MsgBox "Done importing", vbInformation
con.Close
Set con = Nothing
End With
Exit Sub
errH:
MsgBox Err.Description
End Sub
Or........from Excel to SQL Server using a WHERE clause.
Sub InsertInto()
'Declare some variables
Dim cnn As adodb.Connection
Dim cmd As adodb.Command
Dim strSQL As String
'Create a new Connection object
Set cnn = New adodb.Connection
'Set the connection string
cnn.ConnectionString = "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=True;Initial Catalog=Northwind;Data Source=Excel-PC\SQLEXPRESS"
'cnn.ConnectionString = "DRIVER=SQL Server;SERVER=Excel-PC\SQLEXPRESS;DATABASE=Northwind;Trusted_Connection=Yes"
'Create a new Command object
Set cmd = New adodb.Command
'Open the Connection to the database
cnn.Open
'Associate the command with the connection
cmd.ActiveConnection = cnn
'Tell the Command we are giving it a bit of SQL to run, not a stored procedure
cmd.CommandType = adCmdText
'Create the SQL
strSQL = "UPDATE TBL SET JOIN_DT = '2013-01-22' WHERE EMPID = 2"
'Pass the SQL to the Command object
cmd.CommandText = strSQL
'Execute the bit of SQL to update the database
cmd.Execute
'Close the connection again
cnn.Close
'Remove the objects
Set cmd = Nothing
Set cnn = Nothing
End Sub
I'm working on a rec process which will pull data out of a SQL Server database into Excel and out of another application to compare the two sources.
I've written some code that will pull the data into a ADODB record set and drop it into an Excel sheet from a SQL Server view. This works as expected.
I need the query to be more dynamic and as it is quite resource intensive in the real query. I think it would be better to use a stored procedure, passing parameters to the query and only returning the result sets I need.
I don't want the SQL query to be complicated within the VBA though which is why I can't just define the query there.
The following code returns no records to the record set and exits.
Running the stored procedure in Management Studio using the same parameter gives the results expected in SSMS.
Stored procedure:
CREATE PROCEDURE [dbo].[JoshTest]
#AccCode nvarchar(50)
AS
SET NOCOUNT ON;
SELECT
[Account_SKey], [Hierarchy_SKey], [Account_Code], [Leaf]
FROM
[dbo].[VW_DIM_ACCOUNT_LEAF]
WHERE
[Leaf] = #AccCode;
GO
VBA in Excel:
Sub test_stored_proc()
Dim AccountCodeVar As String
AccountCodeVar = Range("ACCCODESEL").Value
Dim osheet As String 'output sheet
Dim orange As String 'output range
osheet = "Output1"
orange = "A3"
Call ConnectSqlServerStoredProc(osheet, orange, AccountCodeVar)
End Sub
Function ConnectSqlServerStoredProc(osheet As String, orange As String, AccountCodeVar As String)
'Clear previous results
Sheets("Output1").Range("A3:D60000").Clear
Dim conn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim sConnString As String
Dim cmd As ADODB.Command
Dim prm As ADODB.Parameter
' Create the connection string.
sConnString = "Provider=SQLOLEDB;Data Source=CSIMCCS01; Initial Catalog=T_EXP_CPM; Integrated Security=SSPI;"
Debug.Print sConnString
' Create the Connection and Recordset objects.
Set conn = New ADODB.Connection
Set rs = New ADODB.Recordset
' Open the connection and execute.
conn.Open sConnString
Set cmd = New ADODB.Command
cmd.CommandText = "JoshTest"
cmd.CommandType = adCmdStoredProc
cmd.ActiveConnection = conn
'set parameter values
Set prm = cmd.CreateParameter(Name:="AccCode", Type:=adVarChar, Direction:=adParamInput, Size:=10)
cmd.Parameters.Append prm
cmd.Parameters("AccCode").Value = "'" & AccountCodeVar & "'"
Debug.Print cmd.Parameters("AccCode").Value
Set rs = cmd.Execute
' Check we have data.
If Not rs.EOF Then
' Transfer result.
Sheets(osheet).Range(orange).CopyFromRecordset rs
' Close the recordset
rs.Close
Else
MsgBox "Error: No records returned.", vbCritical
End If
' Clean up
If CBool(conn.State And adStateOpen) Then conn.Close
Set conn = Nothing
Set rs = Nothing
MsgBox ("Done")
End Function
I looked at several examples of similar questions but they all try to return a single value, such as status / user id etc. rather than a data set.
Worked it out eventually... the issues was that I was putting single quotes either side of the parameter value. I thought that this would be correct as SQL would require them but taking them out of the VBA has resolved the issue.
#Mister 832 - thanks for your help in stepping this through.
In the end the solution was changing:
cmd.Parameters("#AccCode").Value = "'" & AccountCodeVar & "'"
to
cmd.Parameters("#AccCode").Value = AccountCodeVar
Regards
Have you tried adding an # to the parametername?
Set prm = cmd.CreateParameter(Name:="#AccCode", Type:=adVarChar, Direction:=adParamInput, Size:=10)
cmd.Parameters.Append prm
cmd.Parameters("#AccCode").Value = "'" & AccountCodeVar & "'"
I got it working on my pc.
Remove the line Set rs = New ADODB.Recordset and change the recordsetline to Set rs = cmd.Execute
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
I have a simple VBA code that needs to execute a SP from SQL Server with one parameter. I copied the code from a text book, making relevant adjustments, but I keep getting this error.
Here is the code:
Public Sub ExecuteStoredProcAsMethod()
Dim objConn As ADODB.Connection
Dim rsData As ADODB.Recordset
Dim sConnect As String
'Create the conntection string.
sConnect = "Provider=SQLOLEDB;Data Source=MYSERVER; " & _
"Initial Catalog=DisaggregatedPatronage;Integrated Security=SSPI"
'Create the connection and Recordset objects.
Set objConn = New ADODB.Connection
Set rsDate = New ADODB.Recordset
'Open the connection and execute the SP.
objConn.Open sConnect
objConn.spSurveyDataTest "Bus", rsData
'Make sure we got records back
If Not rsData.EOF Then
'Dump the contens of the recodset on the worksheet
Sheet1.Range("A1").CopyFromRecordset rsDate
'Close the recordset
rsData.Close
'Fit the column wirdths to the data
Sheet1.UsedRange.EntireColumn.AutoFit
Else
MsgBox "Error: No records returned. ", vbCritical
End If
'Clean up our ADO objects.
If CBool(objConn.State And adStateOpen) Then objConn.Close
Set objConn = Nothing
Set rsData = Nothing
End Sub
You declare an rsData variable, but you initialize rsDate. Aren't you using the Option Explicit statement?