Hiko.Blog Excel VBA活用術

「Excel VBAで仕事を効率化!初心者でもできる自動化のコツ」

MENU

Accessクエリの実行2

Declare PtrSafe Function FindWindow Lib "user32" Alias "FindWindowA" _
    (ByVal lpClassName As String, ByVal lpWindowName As String) As Long

Declare PtrSafe Function FindWindowEx Lib "user32" Alias "FindWindowExA" _
    (ByVal hWnd1 As Long, ByVal hWnd2 As Long, ByVal lpsz1 As String, ByVal lpsz2 As String) As Long

Declare PtrSafe Function SendMessage Lib "user32" Alias "SendMessageA" _
    (ByVal hWnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam As Any) As Long

Const WM_SETTEXT = &HC

Sub ConnectToOracle()
    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 hwndChild As Long
    
    ' Accessデータベースのパスとクエリ名を指定します
    dbPath = "C:\path\to\your\database.accdb"
    queryName = "YourQueryName"
    
    ' Oracle ODBCドライバの名前、ユーザー名、パスワードを指定します
    odbcDriverName = "Oracle ODBC Driver Connect"
    oracleUsername = "your_username"
    oraclePassword = "your_password"
    
    ' Accessアプリケーションを作成します
    Set accessApp = CreateObject("Access.Application")
    
    ' Accessデータベースを開きます
    accessApp.OpenCurrentDatabase dbPath
    
    ' クエリを実行します
    accessApp.DoCmd.OpenQuery queryName

    ' ODBCドライバのログイン画面が表示されるまで待ちます
    Application.Wait (Now + TimeValue("0:00:05"))

    ' Oracle ODBCドライバのログイン画面のウィンドウハンドルを取得します
    hWnd = FindWindow(vbNullString, odbcDriverName)
    
    If hWnd <> 0 Then
        ' ユーザー名を入力
        hwndChild = FindWindowEx(hWnd, 0, "Edit", vbNullString)
        SendMessage hwndChild, WM_SETTEXT, 0, ByVal oracleUsername
        ' パスワードを入力
        hwndChild = FindWindowEx(hWnd, hwndChild, "Edit", vbNullString)
        SendMessage hwndChild, WM_SETTEXT, 0, ByVal oraclePassword
        ' エンターキーを送信
        SendKeys "~", True
    End If
    
    ' Accessアプリケーションを閉じます
    accessApp.CloseCurrentDatabase
    accessApp.Quit
    Set accessApp = Nothing
End Sub