将数据从SQL Server提取到包含标头的Excel VBA

时间:2016-01-28 15:31:02

标签: sql sql-server vba header

我可以使用VBA成功地将数据从SQL Server提取到Excel,但是我收到的数据没有列标题。

我正在使用此代码:

Dim conn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim sConnString As String

' Create the connection string.
sConnString = "Provider=SQLOLEDB.1;Data Source=hu;" & _
              "Initial Catalog=dd;" & _
              "Integrated Security=SSPI;"

' 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 * TABLE;")

' Check we have data.
If Not rs.EOF Then
    ' Transfer result.
    ActiveSheet.Range("A1").CopyFromRecordset rs
' Close the recordset
    rs.Close
Else
    MsgBox "Error: No records returned.", vbCritical
End If

' Clean up
If CBool(conn.State And adStateOpen) Then conn.Close
Set conn = Nothing
Set rs = Nothing

有没有办法包括标题?

谢谢!

0 个答案:

没有答案