【问题标题】:SQL Server from Excel 2010 VBA - Multiple rows of dataExcel 2010 VBA 中的 SQL Server - 多行数据
【发布时间】:2012-03-17 00:13:42
【问题描述】:

我正在尝试从 SQL Server 中获取多行,然后在 VBA 中对其进行操作。我与数据库的连接正常工作,我可以使用 Range().CopyFromRecordSet() 函数提取我需要的所有数据,但是我只想在 VBA 中操作数据,而不是将工作表放入其中.
使用 Recordset 对象,我可以访问字段名称和第一行数据,但无法访问所有行。
当我使用 Recordset.GetRows() 函数时,我可以访问所有数据,但它没有任何结构,也没有附加到记录的字段名称,因此很难使用。

如何以结构化的方式循环浏览结果中的不同行?

这是我的代码:

Sub grabData()
    Dim dbConn As ADODB.Connection
    Set dbConn = openDBConn()
    Dim results As ADODB.Recordset
    Set results = dbConn.Execute("SELECT Field1, Field2, Field3 FROM Table WHERE Field1 = 'Foobar' AND Field2 > '42'")

    'Cycles through the first row of data'
    For Each f In results.Fields
      Debug.Print f.Name & " " & f
    Next

    'Cycles through all data, but no Column names'
    For Each f In results.GetRows
        Debug.Print f
    Next
End Sub

【问题讨论】:

    标签: vba excel export-to-excel


    【解决方案1】:
    Do While Not results.EOF
       For Each f In results.Fields
          Debug.Print f.Name & " " & f.Value
       Next
       results.MoveNext
    Loop
    

    【讨论】:

    • 太棒了,我知道我一定错过了什么。谢谢!
    猜你喜欢
    • 2014-04-15
    • 2013-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多