【发布时间】:2020-06-18 04:35:44
【问题描述】:
我有以下 VBA 使用此 VBA 中的 SQL 语句从数据库中获取数据:
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
这一切都很完美。
但是,现在我还希望 SQL 中的 cID 的别名在 Excel 文件中显示为 column header。
结果应如下所示:
A B C
1 campaign
2 001
3 002
4 003
5 :
6 :
7
因此,我尝试使用here 的解决方案,并在我的 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
VBA 正在运行。但是,别名不会显示为列名。
我需要在我的 VBA 中进行哪些更改才能使其正常工作?
【问题讨论】:
-
你在哪里定义
mrs? -
感谢您的提示。我编辑了我的问题。我不再收到运行时错误,但别名仍未用作列名。