Pulling Column Names into Excel from SQL query

Ok so I figured it out after 4 attempts, here's the code for the loop.

 'Loop'
 Dim FieldRange As Range
 Set FieldRange = Range("A4")
 Set TableColumns = Range("A4:H4")
 x = 1

 Range("A4").Select

 For Each fld in objMyRecordset.Fields
      ActiveCell.Value = fld.Name
      ActiveCell.Offset(0, x).Select
      x = x + 1 'tick iterator
 Next

 ActiveSheet.Range("A5").CopyFromRecordset objMyRecordset
 Range("A4").Select

You can just set your "x" variable to 0 and then do something like:

x = 0

For Each Field In RS.Fields 'RS being my Recordset variable
    Range("A3").Offset(0, x).Value = Field.Name
    x = x + 1
Next Field

And that will make it a bit easier to read... :)


To make it super simple, do something like this (using Sheet1 and recordset r)

    For i = 0 To r.Fields.Count - 1
        Sheet1.Cells(1, i + 1) = r.Fields(i).Name
    Next i

My usual code is very similar:

For intColIndex = 0 To objMyRecordset.Fields.Count - 1 
    Range("A4").Offset(0, intColIndex).Value = objMyRecordset.Fields(intColIndex).Name
Next