使用SQLOLEDB Provider在Excel VBA中执行SQL查询

时间:2014-03-05 21:31:50

标签: sql sql-server excel excel-vba ado vba

我很想知道如何访问我的SQL数据库中的表,最终允许我插入我在Excel工作表中的数据。我相信我有正确的连接字符串,因为我的声明说我的连接是真的,我可以看到它通过。

但是,到了执行我的

'Select * from dbo.tbl_Cust_Refresh'

我收到无效对象错误。 enter image description here

更新&回答 我回到我的SQL Server,删除了表,重新创建了它,并将我的选择更改为我的DCP.dbo.tbl_Cust_Refresh的名称,并且它工作正常。感谢大家的帮助。

以下是我的代码的最终版本,其中包含一个新的msgbox,用于显示我是否已连接。

Option Explicit
Private CN As ADODB.Connection

Function Connect(Server As String, _
                 Database As String) As Boolean
 Dim canConnect As Boolean
    Set CN = New ADODB.Connection
    On Error Resume Next

    With CN
        ' Create connecting string
'CN.Open "Provider =SQLOLEDB; Data Source=1CLSVHBASQLR01; Integrated Security=SSPI; `Initial Catalog=DCP_PROD; UID=DCPSSRSUser; PWD=Wsfsb@nk-1; Workstation ID=2OPDW058923;"`
' "Provider=sqloledb;Data Source=1CLS; Initial Catalog=DCP;Integrated `Security=SSPI;"`
CN.Provider = "sqloledb"
'CN.Properties("Prompt") = adPromptAlways
CN.Open "Data Source=1CLSVHBASQLR01;" & _
      "Initial Catalog=DCP_PROD;" & _
      "Integrated Security=SSPI"



        ' Open connection
        .Open
    End With
    ' Check connection state
    If CN.State = 0 Then
        Connect = False
    Else
        Connect = True
    End If

    If CN.State = adStateOpen Then
   canConnect = True

MsgBox "connected to server"
Else
MsgBox "Invalid username & password"

End If


End Function

Function Query(SQL As String)

    Dim RS As ADODB.Recordset
    Dim Field As ADODB.Field

    Dim Col As Long

    ' Open up a recordset / run query
    Set RS = New ADODB.Recordset
    'RS.Open SQL, CN, adOpenStatic, adLockReadOnly, adCmdText
    RS.Open SQL, CN, adOpenStatic, adLockOptimistic ', adCmdText

    If RS.State Then
        Col = 1
        ' Output the column headings in the first row
        For Each Field In RS.Fields
            Cells(1, Col) = Field.Name
            Col = Col + 1
        Next Field
        ' Output the results in the rest of the worksheet
        Cells(2, 1).CopyFromRecordset RS
        Set RS = Nothing
    End If
End Function

Function Disconnect()
    ' Close connection
    CN.Close
End Function

Public Sub Run()

    Dim SQL As String
    Dim Connected As Boolean

    ' Our query
    SQL = "SELECT * FROM [DCP].[dbo].[tbl_Cust_Refresh]"
    Debug.Print SQL


    ' Connect to the database
    Connected = Connect("1CLS", "DCP")

    If Connected Then
        ' If connected run query and disconnect
        Call Query(SQL)
        Call Disconnect
    Else
        ' Couldn't connect
        MsgBox "Could Not Connect!"
    End If

End Sub

0 个答案:

没有答案