用Excel VBA连接SQL Server数据库并将表中的数据显示到Excel中

本实例使用VB语言和OLEDB类连接SQL Server 2005数据库。

在sheet1上右键→查看代码,加入如下代码:

Sub admin()
    Dim conn, xRs

    Set conn = CreateObject("ADODB.Connection")
    conn.Open "Provider=SQLOLEDB.1;Persist Security Info=False;User ID=sa;PWD=abc;Initial Catalog=GoodLuck;Data Source=localhost"
    Set xRs = CreateObject("ADODB.RecordSet")
    
    sSql = " Select * from View_S_E"
    xRs.Open sSql, conn, 1, 3

    Sheet1.Cells.Clear
    Sheet1.Range("A1").CopyFromRecordset xRs
    xRs.Close
    
    conn.Close
    Set xRs = Nothing
    Set conn = Nothing
End Sub


你可能感兴趣的:(《GIS程序设计》)