title: VBA macro save SQL query in a csv file
body: <p>I am working on a VBA macro which connects to my database on SQL Server and run some queries and save the results on CSV files... it works fine just when the queries returns data but i have days where the query doesn't return any results, just an empty table. I made a temporary solution based on checking the date and according it the macro runs that query or no... I want to make it other way now in my code so that i don't need to change the date everytime manually...</p>
  
  <p>I tried these solutions : </p>
  
  <pre><code>If (objMyRecordset.EOF = False) Or (objMyRecordset.BOF = False) Then
  </code></pre>
  
  <p>Also this </p>
  
  <pre><code>If objMyRecordset.RecordCount &lt;&gt; 0 Then
  </code></pre>
  
  <p>but the problem is my Recordset is empty because the query doesn't return any rows so it shows me error in <code>objMyRecordset.Open</code>
  I want to add a line of code like this for example : </p>
  
  <pre><code>'// Pseudo Code
  If (the query doesn't return result)  Then 
      ( just the headers will be save on my file )
  Else 
      (do the rest of my code)
  End If
  </code></pre>
  
  <hr>
  
  <p>Here is my code. Any suggestions please ? Thank you very much.</p>
  
  <pre><code>Sub Load_after_cutoff_queryCSV()
  
      Dim objMyConn As ADODB.Connection
      Dim objMyCmd As ADODB.Command
      Dim objMyRecordset As ADODB.Recordset
  
      Dim fields As String
      Dim i As Integer
  
      Set objMyConn = New ADODB.Connection
      Set objMyCmd = New ADODB.Command
      Set objMyRecordset = New ADODB.Recordset
  
  'Open Connection
      objMyConn.ConnectionString = "Provider=SQLOLEDB;Data Source=*****;User ID=*****;Password=*****;"
      objMyConn.Open
  
  'Set and Excecute SQL Command
      Set objMyCmd.ActiveConnection = objMyConn
  
      objMyCmd.CommandText = "SELECT * FROM [vw_X86_LOAD_AFTER_CUTOFF_REPORT_GAMMA]"
  
      objMyCmd.CommandType = adCmdText
  
  'Open Recordset
      Set objMyRecordset.Source = objMyCmd
  
      objMyRecordset.Open
  
      Workbooks.Open Filename:="C:\Reports\load_after_cutoff_postGamma.csv"
      Workbooks("load_after_cutoff_postGamma.csv").Sheets("load_after_cutoff_postGamma").Activate
      ActiveSheet.Range("A2").CopyFromRecordset objMyRecordset
  
       For i = 0 To objMyRecordset.fields.Count - 1
      Worksheets("load_after_cutoff_postGamma").Cells(1, i + 1) = objMyRecordset.fields(i).name
      Next i
  
      Workbooks("load_after_cutoff_postGamma.csv").Sheets("load_after_cutoff_postGamma").Cells.EntireColumn.AutoFit
  
      Workbooks("load_after_cutoff_postGamma.csv").Close SaveChanges:=True
      MsgBox "Your file has been saved as load_after_cutoff_postGamma.csv"
  </code></pre>