At the moment running an SQL query that outputs data to an active sheet.
What I would like to do is when the CommandButton is pressed, instead of pasting the dataset to the ActiveWorkbook to set it to the New Work Book that I have added but I dont know how to set this...
Is there a way where once the new work book opens the data that the SQl query has run can be placed into the new workbook and not the ActiveSheet as I have it setup?
What I would like to do is when the CommandButton is pressed, instead of pasting the dataset to the ActiveWorkbook to set it to the New Work Book that I have added but I dont know how to set this...
Code:
Private Sub CommandButton1_Click() 'open new workbook
With CreateObject("Excel.Application")
.Workbooks.Add
.Visible = True
End With
'Declare variables'
Dim objMyConn As ADODB.Connection
Dim objMyCmd As ADODB.Command
Dim objMyRecordset As ADODB.Recordset
Set objMyConn = New ADODB.Connection
Set objMyCmd = New ADODB.Command
Set objMyRecordset = New ADODB.Recordset
'Open Connection'
objMyConn.ConnectionString = "Provider=SQLOLEDB;Data Source=NP-DATABASE;Initial Catalog=" & ComboBox1.Value & " ;Integrated Security=SSPI;"
objMyConn.ConnectionTimeout = 0
objMyConn.CommandTimeout = 0
objMyConn.Open
'Set and Excecute SQL Command from TextBox'
Set objMyCmd.ActiveConnection = objMyConn
objMyCmd.CommandText = TextBox1.Value ' query run from TextBox
objMyCmd.CommandType = adCmdText
'Open Recordset'
Set objMyRecordset.Source = objMyCmd
objMyRecordset.Open
'include headers from recordset
With objMyRecordset
For i = 1 To .Fields.Count
ActiveSheet.Cells(1, i) = .Fields(i - 1).Name
Next i
End With
'Copy Data to Excel'
ActiveSheet.Range("A2").CopyFromRecordset objMyRecordset
End Sub
Is there a way where once the new work book opens the data that the SQl query has run can be placed into the new workbook and not the ActiveSheet as I have it setup?