Excel VBA初心者ですが、よろしくお願いします。
コーディングの重複を避けるために、オープンとデータベース接続に共通の関数と、それを閉じる別の関数を作成する方法を教えてください。
これが私のコードです。先に進む方法に困っています...
Const connection_string As String = "Provider=SQLOLEDB.1;Password=XXX;Persist Security `Info=True;User ID=sa;Initial Catalog=TESTDB;Data Source=XXXX;"
Sub DuplicateDBConnection()
'Declare variables
Set cn1 = New ADODB.Connection
Set cmd1 = New ADODB.Command
Set rs1 = New ADODB.Recordset
'Open Connection
cn1.ConnectionString = connection_string
cn1.Open
'Set and Excecute SQL Command
Set cmd1.ActiveConnection = cn1
cmd1.CommandText = "Select stock_code, name, sector_id from stock_master"
cmd1.CommandType = adCmdText
cmd1.Execute
'Open Recordset
Set rs1.ActiveConnection = cn1
rs1.Open cmd1
'Copy Data to Excel
ActiveSheet.Range("A1").CopyFromRecordset (rs1)
'Close Connection
rs1.Close
cn1.Close
'Throw Object
Set rs1 = Nothing
Set cn1 = Nothing
End Sub
私の願いは、接続して接続を閉じるためにコードを書き続ける必要がないように、一般的な関数を書くことです。
Sub ConnectDB()
'Codes to connect DB
End Sub
Sub CloseConnnection()
'Codes to close connection
End Sub
Sub ExecuteCode()
ConnectDB
'Execute SQL command to manipulate data on excel and SQL database
CloseConnection
End Sub
Kittoe の提案に基づいて編集し、適切に動作するようになりました。ありがとう!
クラス: A. a. AdoDbHelper と呼ばれるクラス、Private Instancing を作成しました。AdoDbHelper で、「Option Compare Database」を「Option Compare Text」に変更します。
モジュール: このような関数を作成します。
以下のコード:
Const connection_string As String = "Provider=SQLOLEDB.1;Password=XXX;Persist Security `Info=True;User ID=sa;Initial Catalog=TESTDB;Data Source=XXXX;"
Sub Test()
Dim sourceDb As New AdoDbHelper
Dim sourceRs As New ADODB.Recordset
sourceDb.Connect (connection_string)
Set sourceRs = sourceDb.OpenRecordset("Select stock_code, name, sector_id from stock_master")
With sourceRs
'Do stuff!
ActiveSheet.Range("A1").CopyFromRecordset sourceRs
.Close
End With
sourceDb.Disconnect
Set sourceRs = Nothing
Set sourceDb = Nothing
End Sub