VBA包含SQL查询头

时间:2017-03-02 03:09:52

标签: sql vba excel-vba excel

我需要添加表头以包含在我的VBA代码中,该代码连接到SQL。代码正在运行(因为它在新的工作表上吐出SQL结果),但它并没有抓住标题。

有人可以帮忙吗?

Sub SpectrumADGroupMapping()

    'Start Declarations'
    Dim Cn As ADODB.Connection
    Dim rs As ADODB.Recordset

    'Connection string to SQL server/DB (Windows Auth)
    Set Cn = New ADODB.Connection
    Cn.ConnectionString = "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=True;Data Source=TEST;Use Procedure for Prepare=1;Auto Translate=True;Packet Size=4096;Workstation ID=TESTPC;Use Encryption for Data=False;Tag with column collation when possible=False;Initial Catalog=TESTDBNAME"
    Cn.Open 

    Set and Execute SQL Command
    Set rs = New ADODB.Recordset
    rs.ActiveConnection = Cn
    rs.Open "Select top 50* from TestTable order by creationDate desc"

    'Copy Data to Excel
    Worksheets.Add(After:=Worksheets(1)).Name = "TestWorkSheet"
    Range("A2").CopyFromRecordset rs

    Cn.Close

End Sub

1 个答案:

答案 0 :(得分:0)

以下内容应该有效。 (我只是将它从我的一个电子表格中拖出来 - 只是更改名称以保护无辜者。)

' Write out the Field names as column headings
Dim c As Long
For c = 1 To rs.Fields.Count
    With Worksheets("TestWorkSheet").Cells(1, c)
        .Value = rs.Fields(c - 1).Name

        'The rest is just how we format the headings - leave it in or take it out
        .Font.Bold = True
        .Interior.Pattern = xlSolid
        .Interior.PatternColorIndex = xlAutomatic
        .Interior.ThemeColor = xlThemeColorDark1
        .Interior.TintAndShade = -0.149998474074526
        .Interior.PatternTintAndShade = 0
        .HorizontalAlignment = xlCenter
        .VerticalAlignment = xlCenter
        .WrapText = True
        'End of formatting of headings

    End With
Next c

将该代码放在Range("A2").CopyFromRecordset rs行之前(您应该将其编码为Worksheets("TestWorkSheet").Range("A2").CopyFromRecordset rs - 在使用Range Cells时,确定您要引用的工作表始终是一个好主意。 1}}等。)