■ 最新の投稿

【VBA×WScript.Shell】SendKeysで外部アプリを自動操作する方法

VBAとWScript.Shellを組み合わせれば、Excelマクロから他のアプリケーションを自動で操作することが可能です。

特に SendKeys を使うことで、キーボード操作を模倣し、外部アプリへの文字入力やコマンド送信ができます。

■ 参照設定なしで使える!

CreateObjectでWScript.Shellを使い、メモ帳に「Spring Comes」と書く。

Declare PtrSafe Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)

Sub SendKeysToNotepad()

    Dim wsh As Object
    Set wsh = CreateObject("WScript.Shell")
    
    ' メモ帳を起動
    wsh.Run "notepad"
    Sleep 1000  ' 1秒待つ(アプリ起動待機)
    
    ' メモ帳をアクティブにして入力
    wsh.SendKeys "Spring comes"
    
End Sub

■ 参照設定ありで使える!

WScript.Shellを使い、メモ帳に「Spring Comes」と書く。

参照設定 → 「Windows Script Host Object Model」 を追加します。

Declare PtrSafe Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)

Sub SendKeysToNotepad()

    Dim wsh As WshShell
    Set wsh = New WshShell
    
    ' メモ帳を起動
    wsh.Run "notepad"
    Sleep 1000  ' 1秒待つ(アプリ起動待機)
    
    ' メモ帳をアクティブにして入力
    wsh.SendKeys "Spring comes"
    
End Sub

Comments

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です