AppActivateとSendKeysを使って、Excel VBAで初歩的なRPA的なことをしているひともいるかと思います。
キー送信をするだけなら簡単ですが、難しいのは、メッセージボックスに反応することではないでしょうか?
メッセージボックスの内容を取得する方法を紹介します。
Captionを指定して、指定したCaptionに合致するメッセージボックスのPromptを取得します。
Private Declare PtrSafe Function FindWindowW Lib "user32" (ByVal lpClassName As LongPtr, ByVal lpWindowName As LongPtr) As LongPtr
Private Declare PtrSafe Function GetWindowTextLengthW Lib "user32" (ByVal hwnd As LongPtr) As Long
Private Declare PtrSafe Function GetDlgItem Lib "user32" (ByVal hDlg As LongPtr, ByVal nIDDlgItem As Long) As LongPtr
Private Declare PtrSafe Function FindWindowExW Lib "user32" (ByVal hWnd1 As LongPtr, ByVal hWnd2 As LongPtr, ByVal lpsz1 As LongPtr, ByVal lpsz2 As LongPtr) As LongPtr
Private Declare PtrSafe Function GetWindowTextW Lib "user32" (ByVal hwnd As LongPtr, ByVal lpString As LongPtr, ByVal cch As Long) As Long
Private Function GetPrompt(ByVal Caption As String) As String
Dim hWndDialog As LongPtr
Dim hWndMessage As LongPtr
Dim nLength As Long
Dim sText As String
hWndDialog = FindWindowW(0, StrPtr(Caption))
If hWndDialog Then
hWndMessage = GetDlgItem(hWndDialog, &HFFFF&)
If hWndMessage Then
nLength = GetWindowTextLengthW(hWndMessage) + 1
sText = String(nLength, vbNullChar)
nLength = GetWindowTextW(hWndMessage, StrPtr(sText), nLength)
GetPrompt = Mid(sText, 1, nLength)
End If
End If
End Function
Sub main()
'実験するには、たとえば次の内容をもつVBSファイルを作っておきます。
' MsgBox "処理を続行しますか?",vbOKOnly, "Application Error"
'このマクロを実行する前に、作ったVBSファイルを実行して、メッセージを表示状態にします。
'このマクロを実行すると、"Application Error"から逆引きして、"処理を続行しますか?"を取得します。
Debug.Print GetPrompt("Application Error")
End Sub