Excel VBA SendKeysでメモ帳を操作

Listviewで選択している行などから、そのデータソースになっているテキストファイルをWindowsのメモ帳(notepad.exe)で開き、所定の行にフォーカスする方法です。SendKeysを使ってメモ帳の操作を行います。
プログラム名とテキストファイルのパスを渡してメモ帳を起動した後、検索操作と行を探すための検索キーワードなどをSendKeysでメモ帳に送ります。
<下準備>
適当なテキストファイルを作り、text.txt と名前をつけてCドライブの直下に置く
<ポイント>
SendKeys の後に処理が終わるのを待つためにスリープを入れています。入れなくても動くかも。
SendKeys でCtrl+Fなどを送る場合、"^F"ではなく"^f"としないとうまく動かないようです。
行を指定する場合は、SendKeys "^g" と SendKeys "[行番号(数値ではなく文字列)]"とすればよいです。
ソースコード
標準モジュールに下のコードを貼り付けて使ってください。
VB6の場合、少しコードの書き方が異なります。
Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long) Public Sub Sample() Dim filePath As String: _ filePath = "C:\test.txt" Call openTextWithNotePad(filePath, 3, 300, "あいうえお") End Sub
'以下はExcelの場合 Public Sub openTextWithNotePad(_
filePath As String, _ openMode As Integer, _ waitTime As Long, _ target As String)
On Error GoTo ErrorHandler
Dim shellApp As String
'メモ帳と開くファイル名を組み合わせる shellApp = "notepad.exe " & filePath Dim taskID As Double
'メモ帳を起動しつつ、タスクIDを取得 'openModeはウインドウの状態 3は全画面 taskID = Shell(shellApp, openMode)
'タスクIDを指定してメモ帳をアクティブにする AppActivate (taskID)
Sleep (waitTime)
'メモ帳で検索(Ctrl+Fを押す)する操作 Application.SendKeys "^f", True Sleep (waitTime)
'検索窓に検索する文字列を入力する操作 Application.SendKeys target, True Sleep (waitTime)
'Enterキーを押す操作 Application.SendKeys "~", True
Exit Sub
ErrorHandler:
MsgBox "Error"
End Sub
'以下はVB6の場合
Public Sub openTextWithNotePad( _ filePath As String, _ openMode As Integer, _ waitTime As Long, _ target As String) On Error GoTo ErrorHandler Dim shellApp As String shellApp = "notepad.exe " & filePath
Dim taskID As Double taskID = Shell(shellApp, openMode) AppActivate (taskID) Dim WshShell As Object Set WshShell = CreateObject("wscript.shell") Sleep (waitTime) WshShell.SendKeys "^(f)", True Sleep (waitTime) WshShell.SendKeys target, True Sleep (waitTime) WshShell.SendKeys "~", True
Exit Sub ErrorHandler: MsgBox "Error" End Sub