ODBCのデータソースを、VBAのコードで作成する

http://www.accessclub.jp/bbs5/0020/vba5763.html
http://support.microsoft.com/kb/287668/JA/
次の例では、SQLConfigDataSource の API 呼び出しを使用してシステム DSN を作成します。この例では、C:\Northwind.mdb にあるサンプル データベース Northwind.mdb のデータ ソースを作成します。

サンプル データベース Northwind.mdb を C ドライブのルート ディレクトリにコピーします。
新しい Access データベースを作成します。
モジュールを作成し、Declarations セクションに次の行を入力します。

Option Explicit
Const ODBC_ADD_SYS_DSN = 4 ‘Add data source
Const ODBC_CONFIG_SYS_DSN = 5 ‘Configure (edit) data source
Const ODBC_REMOVE_SYS_DSN = 6 ‘Remove data source

Private Declare Function SQLConfigDataSource Lib “ODBCCP32.DLL” (ByVal _
hwndParent As Long, ByVal fRequest As Long, ByVal _
lpszDriver As String, ByVal lpszAttributes As String) As Long

次のプロシージャを入力します。

Function Build_SystemDSN(DSN_NAME As String, Db_Path As String)

Dim ret%, Driver$, Attributes$

Driver = “Microsoft Access Driver (*.MDB)” & Chr(0)
Attributes = “DSN=” & DSN_NAME & Chr(0)
Attributes = Attributes & “Uid=Admin” & Chr(0) & “pwd=” & Chr(0)
Attributes = Attributes & “DBQ=” & Db_Path & Chr(0)

ret = SQLConfigDataSource(0, ODBC_ADD_SYS_DSN, Driver, Attributes)

‘ret is equal to 1 on success and 0 if there is an error
If ret <> 1 Then
MsgBox “DSN Creation Failed”
End If

End Function

イミディエイト ウィンドウに次の行を入力し Enter キーを押します。
? Build_SystemDSN(“My SampleDSN”,”c:\Northwind.mdb”)
[スタート] ボタンをクリックし、[設定] をポイントし、[コントロール パネル] をクリックします。
コントロール パネルで、[ODBC データ ソース]、[ODBC データ ソース (32 ビット)]、または [32 ビット ODBC] をダブルクリックします。
[システム DSN] タブをクリックします。[システム データ ソース] ボックスの一覧に My SampleDSN が追加されています。