0
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

SQLServer VBAでリモート接続

Last updated at Posted at 2023-04-18
Option Explicit


'Microsoft OLE DB Provider for SQL Server→ADOでSQLServerにアクセスするためのプロバイダー。
Private Const PROVIDER As String = "SQLOLEDB"

Private Const DATA_SOURCE As String = "192.168.0.1"   'サーバ名
Private Const DATABASE As String = "TEST_DB"         'データベース名

'SQL Server認証で接続する場合
Private Const USER_ID As String = "sa"        'ユーザID
Private Const PASSWORD As String = "hogehuga"       'ユーザパスワード

Sub sample()
    On Error GoTo ERR_HANDLER
    Dim strSQL As String
    Dim i As Long

    '--------------------------------
    ' データベース接続
    '--------------------------------
    Dim cn As New ADODB.Connection

'    'Windows認証で接続する場合
'    cn.connectionString = "Provider=" & PROVIDER _
'                        & ";Data Source=" & DATA_SOURCE _
'                        & ";Initial Catalog=" & DATABASE _
'                        & ";Trusted_Connection=Yes"
'    cn.Open


   'SQL Server認証で接続する場合
   cn.connectionString = "Provider=" & PROVIDER _
                       & ";Data Source=" & DATA_SOURCE _
                       & ";Initial Catalog=" & DATABASE _
                       & ";user id=" & USER_ID _
                       & ";password=" & PASSWORD
   
   Debug.Print (cn.connectionString)
   cn.Open

    '--------------------------------
    ' SQLの実行
    '--------------------------------
    Dim rs As New ADODB.Recordset
    strSQL = "SELECT * FROM dbo.test;"
    rs.Open strSQL, cn

    '取得データをセルに一括出力
    rs.MoveFirst
    ActiveSheet.Range("A1").CopyFromRecordset rs
    'データベース切断
    Call disconnectDB(cn, rs)

Exit Sub

ERR_HANDLER:

    'エラーメッセージ
    Debug.Print Err.Number & ")" & Err.Description
    'データベース切断
    Call disconnectDB(cn, rs)
    
End Sub
Sub disconnectDB(cn As ADODB.Connection, rs As ADODB.Recordset)
    'データベース切断
    If Not rs Is Nothing Then
        If rs.State = adStateOpen Then rs.Close
        Set rs = Nothing
        End If
    If Not cn Is Nothing Then
        If cn.State = adStateOpen Then cn.Close
        Set cn = Nothing
    End If

End Sub

0
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?