Sub RunAccessQueryAndLoginToOracle()
Dim accessApp As Object
Dim dbPath As String
Dim queryName As String
Dim odbcDriverName As String
Dim oracleUsername As String
Dim oraclePassword As String
Dim hWnd As Long
Dim startTime As Double
' Accessデータベースのパスとクエリ名を指定します
dbPath = "C:\path\to\your\database.accdb"
queryName = "YourQueryName"
' Oracle ODBCドライバの名前、ユーザー名、パスワードを指定します
odbcDriverName = "Oracle ODBC Driver"
oracleUsername = "your_username"
oraclePassword = "your_password"
On Error GoTo ErrorHandler
' Accessアプリケーションを作成します
Set accessApp = CreateObject("Access.Application")
' Accessデータベースを開きます
accessApp.OpenCurrentDatabase dbPath
' クエリを実行します
accessApp.DoCmd.OpenQuery queryName
' ODBCドライバのログイン画面が表示されるまで待ちます
startTime = Timer
Do While Timer < startTime + 5 ' 5秒待ちます
DoEvents
Loop
' Oracle ODBCドライバのログイン画面に自動でIDとパスワードを入力します
hWnd = FindWindow(vbNullString, "Oracle ODBC Driver Connect")
If hWnd <> 0 Then
' ユーザー名を入力
SendKeys oracleUsername, True
SendKeys "{TAB}", True
' パスワードを入力
SendKeys oraclePassword, True
SendKeys "{ENTER}", True
Else
MsgBox "Oracle ODBC Driver Connectウィンドウが見つかりません。", vbExclamation
End If
' Accessアプリケーションを閉じます
accessApp.CloseCurrentDatabase
accessApp.Quit
Set accessApp = Nothing
Exit Sub
ErrorHandler:
MsgBox "エラーが発生しました: " & Err.Description, vbCritical
On Error Resume Next
If Not accessApp Is Nothing Then
accessApp.CloseCurrentDatabase
accessApp.Quit
Set accessApp = Nothing
End If
End Sub
' FindWindow API関数を宣言します
Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" _
(ByVal lpClassName As String, ByVal lpWindowName As String) As Long