2016年4月8日 星期五

excel vba sql server select query

Reference:
Query MS SQL Server With Excel VBA

' Before we can start you’ll need to add a reference to your VBA project:
' Microsoft ActiveX Data Objects x.x Library

Option Explicit
Private Conn As ADODB.Connection

Function ConnectToDB(Server As String, Database As String) As Boolean

    Set Conn = New ADODB.Connection
    On Error Resume Next
   
    Conn.ConnectionString = "Provider=SQLOLEDB.1; Integrated Security=SSPI; Server=" & Server & "; Database=" & Database & ";"
    Conn.Open
   
    If Conn.State = 0 Then
        ConnectToDB = False
    Else
        ConnectToDB = True
    End If

End Function

Function Query(SQL As String)

    Dim recordSet As ADODB.recordSet
    Dim Field As ADODB.Field

    Dim Col As Long

    Set recordSet = New ADODB.recordSet
    recordSet.Open SQL, Conn, adOpenStatic, adLockReadOnly, adCmdText

    If recordSet.State Then
        Col = 1
        For Each Field In recordSet.Fields
            Cells(1, Col) = Field.Name
            Col = Col + 1
        Next Field

        Cells(2, 1).CopyFromRecordset recordSet
        Set recordSet = Nothing
    End If
End Function

Public Sub Run()

    Dim SQL As String
    Dim Connected As Boolean

    SQL = "SELECT * FROM QUOTA_Quota"

    Connected = ConnectToDB("SQL_SERVER", "DB_Name")

    If Connected Then
        Call Query(SQL)
       
        Conn.Close
    Else
        MsgBox "Huston we have a problem!"
    End If

End Sub

沒有留言:

張貼留言