I need some help.
I have the following working VBA to import data into Excel for a stored procedure.
Challenge is how to modify the code to run multiple stored procedures and paste it on different pages.
Please help.
Sub Macro1()
' Create a connection object.
Dim cnPubs As ADODB.Connection
Set cnPubs = New ADODB.Connection
' Provide the connection string.
Dim strConn As String
'Use the SQL Server OLE DB Provider.
strConn = "PROVIDER=SQLOLEDB;"
'Connect to the Pubs database on the local server.
strConn = strConn & "DATA SOURCE=PC\SQL2014;INITIAL CATALOG=Option Database;"
'Use an integrated login.
strConn = strConn & " INTEGRATED SECURITY=sspi;"
'Now open the connection.
cnPubs.Open strConn
' Create a recordset object.
Dim rsPubs As ADODB.Recordset
Set rsPubs = New ADODB.Recordset
With rsPubs
' Assign the Connection object.
.ActiveConnection = cnPubs
' Extract the required records.
.Open "EXEC sp_Week_Option1_01_Export"
' Copy the records into cell A1 on Sheet1.
Sheet4.Range("A2").CopyFromRecordset rsPubs
For intColIndex = 0 To rsPubs.Fields.Count - 1
Range("A1").Offset(0, intColIndex).Value = rsPubs.Fields(intColIndex).Name
Next
' Tidy up
.Close
End With
cnPubs.Close
Set rsPubs = Nothing
Set cnPubs = Nothing
'
End Sub
I modified to the following but I feel it's not the most efficient way. I am thinking creating a loop. Please help:
Sub Macro1()
' Create a connection object.
Dim cnPubs As ADODB.Connection
Set cnPubs = New ADODB.Connection
' Provide the connection string.
Dim strConn As String
'Use the SQL Server OLE DB Provider.
strConn = "PROVIDER=SQLOLEDB;"
'Connect to the Pubs database on the local server.
strConn = strConn & "DATA SOURCE=PC\SQL2014;INITIAL CATALOG=Option Database;"
'Use an integrated login.
strConn = strConn & " INTEGRATED SECURITY=sspi;"
'Now open the connection.
cnPubs.Open strConn
' Create a recordset object.
Dim rsPubs As ADODB.Recordset
Dim rsPubs2 As ADODB.Recordset
Set rsPubs = New ADODB.Recordset
Set rsPubs2 = New ADODB.Recordset
With rsPubs
' Assign the Connection object.
.ActiveConnection = cnPubs
' Extract the required records.
.Open "EXEC sp_Week_Option1_01_Export"
' Copy the records into cell A1 on Sheet1.
Sheet4.Range("A2").CopyFromRecordset rsPubs
For intColIndex = 0 To rsPubs.Fields.Count - 1
Sheet4.Range("A1").Offset(0, intColIndex).Value = rsPubs.Fields(intColIndex).Name
Next
' Tidy up
.Close
End With
With rsPubs2
' Assign the Connection object.
.ActiveConnection = cnPubs
' Extract the required records.
.Open "sp_Week_Option1_01_Export_Crosstab"
' Copy the records into cell A1 on Sheet1.
Sheet9.Range("A2").CopyFromRecordset rsPubs2
For intColIndex = 0 To rsPubs2.Fields.Count - 1
Sheet9.Range("A1").Offset(0, intColIndex).Value = rsPubs2.Fields(intColIndex).Name
Next
' Tidy up
.Close
End With
cnPubs.Close
Set rsPubs = Nothing
Set cnPubs = Nothing
'
End Sub