1

I wrote the following VBA code to connect to an Oracle SQL database and run a query, then export to a new Excel workbook. The query is returning the correct information, but is not returning the column headers. Any help is appreciated.

Sub MACRO1()

  Dim conn As ADODB.Connection
  Dim rs As ADODB.Recordset
  Dim sConnString As String
  Dim wbNew As Workbook  ' Define a variable for the new workbook

  ' Create the connection string.
  sConnString = "Driver={Oracle in OraClient11g_home1};Dbq=EXAMPLEDB;Uid=USERNAME;Pwd=PASSWORD;"

  ' 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 rs = conn.Execute("SELECT COLUMN1, COLUMN2, COLUMN3 FROM TABLE1 A WHERE FILTER1 = 'OPERATING' AND FILTER2 in('XY') AND FILTER3 LIKE ('EXAMPLE')")

  ' Check we have data.
  If Not rs.EOF Then
    ' Create a new workbook
    Set wbNew = Workbooks.Add

    ' Copy data to the new workbook (starting from A1)
    wbNew.Sheets(1).Range("A1").CopyFromRecordset rs

  Else
    MsgBox "Error: No records returned.", vbCritical
  End If

  ' Close the recordset and connection
  rs.Close
  If CBool(conn.State And adStateOpen) Then conn.Close

  ' Clean up
  Set conn = Nothing
  Set rs = Nothing
  Set wbNew = Nothing  ' Release the reference to the new workbook

End Sub

My alternative is to write SQL code to manually input the column headers in the sheet but would like to avoid this if possible.

1 Answer 1

2
' Check we have data.
  Dim n As Long
  If Not rs.EOF Then
  
    ' Create a new workbook
    Set wbNew = Workbooks.Add
    With wbNew.Sheets(1)
        ' Header
        For n = 1 To rs.Fields.Count
            .Cells(1, n) = rs.Fields(n - 1).Name
        Next
    
        ' Copy data to the new workbook (starting from A2)
        .Range("A2").CopyFromRecordset rs
    End With

  Else
        MsgBox "Error: No records returned.", vbCritical
  End If

Not the answer you're looking for? Browse other questions tagged or ask your own question.