I am a bit new to this so my apologies in advance for any mistakes. I am trying to open and execute a sql query which is saved in C drive. The sql works fine. I did not write that sql and it is a very big file so would not like to add the code in VBA. I have been searching on this site and other places but struggling to make this work. I have had some or the other problem each time. I am pasting the code below for you to have a look and help me please. I have created this function which I am using in my VBA code.
Public Function ss()
'Open Connection
Dim oCon As ADODB.Connection
Set oCon = New ADODB.Connection
'Set Connection String
Dim sCon As String
sCon = "Provider=SQLOLEDB;Persist Security Info=True;User
ID='*****';Password='*****';Initial Catalog=****;Data Source=*******;Use
Procedure for Prepare=1;Auto Translate=True;Packet Size=4096;Use Encryption
for Data=False;Tag with column collation when possible=False"
oCon.Open sCon 'Connect established
'Create recordset
Dim ps As ADODB.Recordset
Set ps = New ADODB.Recordset
'Set & execute SQL Command
Dim pCMD As ADODB.Command
Set pCMD = New ADODB.Command
Set pCMD.ActiveConnection = oCon
Dim filename As String
filename = "C:\Users\???????????\******.sql"
'select data
pCMD.CommandText =
CreateObject("scripting.filesystemobject").opentextfile(filename).ReadAll()
Set ps = pCMD.Execute(, , adCmdText)
Debug.Print ps.GetRows
If ps.EOF = False Then Sheets("Sheet2").Range("A1").CopyFromRecordset ps
'Close connection
Set ps = Nothing
Set pCMD = Nothing
oCon.Close
Set oCon = Nothing
End Function
Debug.Print has only been used to see the result but it is showing the same error "Run-time error '3704' Operations is not allowed when the object is closed. After trying so many different things I am not sure what is it that I am doing wrong.
Can someone please help?
Any help will be really appreciated.