将值从SQL Server导入Excel

时间:2017-10-25 14:38:09

标签: excel vba ado

我无法将值从SQL Server导入到Excel。有人可以帮忙:

Dim oConn As ADODB.Connection
Private Sub ConnectDB()

    Set oConn = New ADODB.Connection
    oConn.Open "Provider=SQLOLEDB; " & _
            "Data Source=ServerName; " & _
            "Initial Catalog=MyDB;" & _
            "Trusted_Connection=yes;"
End Sub
Public Sub ExportDataToDB()
    Dim rs As ADODB.Recordset
    ConnectDB
    Set rs = New ADODB.Recordset
    Dim strSql As String

    strSql = "select t.col1, t.col2 from Table t"

    rs.Open strSql, oConn

    Sheet1.Range("A2").CopyFromRecordset rs

    CloseDBConn
End Sub

Private Sub CloseDBConn()
    oConn.Close
End Sub

连接成功。没有错误。查询不为空,但没有任何内容返回到工作表。

1 个答案:

答案 0 :(得分:1)

如果您只想从数据库中读取一组记录,例如将记录的当前状态写入工作表,则应将CursorType的{​​{1}}属性指定为{{ 1}} 以下是Microsoft文档的链接:https://docs.microsoft.com/en-us/sql/ado/guide/data/types-of-cursors-ado