使用Outlook连接到SQL Server数据库

Jua*_* M. 3 sql sql-server vba outlook-vba

我想使用Outlook宏连接到MS SQL Server数据库.但我不知道代码是错还是我需要添加一个库/驱动程序或者这里发生了什么,但它不起作用.

Private Sub Application_Startup()
On Error GoTo ExitHere
    'adodb connection to other database
    stg_cn.Open "Provider = SQLOLEDB;" & _
                        "Data Source = 192.168.100.100;" & _
                        "Initial Catalog = hugeDB;" & _
                        "Integrated Security=SSPI;" & _
                        "User ID = oneuser;" & _
                        "Password = onepassword;"

    sQuery = "SELECT * FROM documents where location = 'IE'"

    'set reference to query
    Set cmd = New ADODB.Command
        cmd.ActiveConnection = stg_cn
        cmd.CommandType = adCmdText
        cmd.CommandText = sQuery
    Set rs = cmd.Execute
    Do While Not rs.EOF
        For i = 0 To rs.Fields.count - 1
            MsgBox (i + 1)
        Next
        rs.MoveNext
    Loop
ExitHere:
    If Not stg_cn Is Nothing Then stg_cn.Close
    Set rs = Nothing
    Set stg_cn = Nothing
    Exit Sub

End Sub
Run Code Online (Sandbox Code Playgroud)

Cod*_*bia 8

在眼睛测试中,我无法弄清楚什么是错的,我认为它必须对你进行ADO操作的方式做些什么.

但我只是把我编写的最后一个宏用于从Macro连接到SQL-Server.希望能帮助到你.

Private Sub Workbook_Open()
On Error GoTo ErrorHandler
    '**************************************Initialize Variables**************************************
    sServer = "<SQL SERVER Server>"
    sDBName = "<SQL SERVER DB>"

    '**************************************Open Connection**************************************
    'adodb connection to other database
    stg_cn.Open "Provider=SQLOLEDB;Data Source=" & sServer & _
                  ";Initial Catalog=" & sDBName & _
                  ";Integrated Security=SSPI;"

    sQuery = "SELECT * " & _
             "FROM Table "

    'set reference to query
    Set cmd = New ADODB.Command
        cmd.ActiveConnection = stg_cn
        cmd.CommandType = adCmdText
        cmd.CommandText = sQuery
    Set rs = cmd.Execute
    Do While Not rs.EOF
        For i = 0 To rs.Fields.Count - 1
            <PERFORM OPERATIONS>
        Next
        rs.MoveNext
    Loop

ExitHere:
    If Not stg_cn Is Nothing Then stg_cn.Close
    Set rs = Nothing
    Set stg_cn = Nothing
    Exit Sub

End Sub
Run Code Online (Sandbox Code Playgroud)