I have the following VBA to get datas from the database using the SQL statement in this VBA:
Sub ConnectDB5()
Dim conn As New ADODB.Connection
Dim rs As New ADODB.Recordset
Dim dateVar As Date
Set conn = New ADODB.Connection
conn.ConnectionString = "DRIVER={MySQL ODBC 5.1 Driver}; SERVER=localhost; DATABASE=bi; UID=username; PWD=password; OPTION=3"
conn.Open
strSQL = " SELECT " & _
" cID AS Campaign " & _
" FROM PDW_DIM_Offers_Logistics_history " & _
" WHERE DATE(insert_timestamp) = ""2020-02-24"" "
Set rs = New ADODB.Recordset
rs.Open strSQL, conn, adOpenStatic
Sheet4.Range("A1").CopyFromRecordset rs
rs.Close
conn.Close
End Sub
All this works perfectly.
However, now I also want that the alias for the cID in the SQL is displayed as column header in the Excel file.
The result should look like this:
A B C
1 campaign
2 001
3 002
4 003
5 :
6 :
7
Therefore, I tried to go with the solution from here and entered the code in my VBA:
Sub ConnectDB6()
Dim conn As New ADODB.Connection
Dim rs As New ADODB.Recordset
Dim dateVar As Date
Set conn = New ADODB.Connection
conn.ConnectionString = "DRIVER={MySQL ODBC 5.1 Driver}; SERVER=localhost; DATABASE=bi; UID=username; PWD=password; OPTION=3"
conn.Open
strSQL = " SELECT " & _
" cID AS Campaign " & _
" FROM PDW_DIM_Offers_Logistics_history " & _
" WHERE DATE(insert_timestamp) = ""2020-02-24"" "
Set rs = New ADODB.Recordset
rs.Open strSQL, conn, adOpenStatic
For iCols = 0 To rs.Fields.Count - 1
Sheet4.Cells(1, iCols + 1).Value = rs.Fields(iCols).Name
Next
Sheet4.Range("A1").CopyFromRecordset rs
rs.Close
conn.Close
End Sub
The VBA is running through. However, the alias is not displayed as column name.
What do I need to change in my VBA to make it work?
mrs?