sql - 如何在VBA中获取列名?

标签 sql database vba excel

我创建了一个模块,我在其中使用存储过程从 SQL DB 读取数据,并且我正在获取所有必需的数据,但我的要求是我还需要所有列名称/标题。而且我无法对名称进行硬编码,因为我正在将数据行转换为存储过程中的列。

这是我写的代码:

ConnStr = "PROVIDER=SQLOLEDB.1;"
ConnStr = ConnStr & "DATA SOURCE=" & dataSrc & "; INITIAL CATALOG=" & iCatalog & "; "
ConnStr = ConnStr & "User ID = " & dbUserId & "; Password = " & dbPassword

On Error GoTo ErrHandler

DBConn.Open ConnStr

' Create a recordset object.
Dim rsCounter As ADODB.Recordset
Set rsCounter = New ADODB.Recordset
Dim startDate As String, endDate As String, query As String

query = "Exec ReadCntrs 0, '12/01/2011', '12/30/2011'"

With rsCounter
    ' Assign the Connection object.
    .ActiveConnection = DBConn

    .Open query
    ' Copy the records into cell A1 on Sheet1.
    Sheet1.Range("A1").CopyFromRecordset rsCounter

    ' Tidy up
    .Close
End With

DBConn.Close
Set rsCounter = Nothing
Set DBConn = Nothing

ExitHere:
    On Error Resume Next
    DBConn.Close: Set DBConn = Nothing
    Err.Clear
    Exit Sub

ErrHandler:
    MsgBox Err.Number & Err.Description, vbExclamation
    Resume ExitHere

End Sub

最佳答案

With rsCounter
    ' Assign the Connection object.
    .ActiveConnection = DBConn

    .Open query

    ' Write the column names into cell A1 on Sheet1.
    Dim counter As Long
    For counter = 0 To rsCounter.Fields.Count - 1
      Sheet1.Range("A1").Offset(, counter).Value = rsCounter.Fields(counter).Name
    Next

    ' Copy the records into cell A2 on Sheet1.
    Sheet1.Range("A2").CopyFromRecordset rsCounter

    ' Tidy up
    .Close
End With

关于sql - 如何在VBA中获取列名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7150054/

相关文章:

.net - 如何捕获带有替换参数的 SQL? (.NET,SqlCommand)

带有 LEFT JOIN (SELECT) ORDER 和 LIMIT 的 MySQL 查询

mysql - 如何在SAS中自动添加id

database - Clickhouse - 是否可以在 1 个命令中更改集群中的表

vba - 不区分大小写的格式

sql - PostgreSQL:间隔 '10 DAY' 和当前行之间的范围

node.js - 在 OSX 上安装和运行 MongoDB

database - 在 CouchDB 中使用 map reduce 输出更少的行

excel - Outlook 通讯簿搜索(无循环?)

vba - 创建一个循环,直到脚本使用所有单元格