OnKeyメソッドのプロシージャに引数を渡す
調べ事中たまたま見つけたのでメモる。
ExcelVBAのApplication.OnKeyメソッドで、シート上でのキー押下時に呼び出すプロシージャを設定できるが、このプロシージャに引数を渡すことができるようだ。ってか、できた。今までキーごとにFunctionを定義していてかなりへぼへぼだったのでかなりうれしい。
# Excelでキーイベントひろう人なんてあまりいないだろうなぁ…。
Application.Onkey "a", "Proc" # なし Application.Onkey "a", "'Proc 1'" # 1 Application.Onkey "a", "'Proc 1, ""str""'" # 1, "str"
' Option Explicit ' グローバル変数 Dim gvKeyCodes As Variant Dim gvFireTime As Variant Dim gnX As Integer, gnY As Integer ' イベントタイプ Enum EventType KeyEvent ' キーイベント TimerEvent ' タイマーイベント End Enum ' 初期化 Sub Init() Dim vCode As Variant gnX = 4 gnY = 4 gvKeyCodes = Array("{RIGHT}", "{LEFT}", "{UP}", "{DOWN}", " ", "S", "Q") For Each vCode In gvKeyCodes Application.OnKey vCode, "'HandleEvent KeyEvent, """ & vCode & """'" Next End Sub ' イベント処理 Function HandleEvent(nType As EventType, vValue As Variant) Select Case nType Case KeyEvent Debug.Print "KeyEvent: " & vValue Select Case vValue Case "S" SetTimer 1 Case "Q" Quit Case "{RIGHT}" Move 1, 0 Case "{LEFT}" Move -1, 0 Case "{DOWN}" Move 0, 1 Case "{UP}" Move 0, -1 Case " " Case Else End Select Case TimerEvent Debug.Print "TimerEvent: " & vValue Move 0, 1 SetTimer 1 Case Else End Select End Function ' 移動 Function Move(x As Integer, y As Integer) If gnX + x > 0 And gnY + y > 0 Then ActiveSheet.Cells(gnY, gnX) = " " gnX = gnX + x gnY = gnY + y ActiveSheet.Cells(gnY, gnX) = "@" End If End Function ' タイマー設定 Function SetTimer(nTime As Integer) Dim nHour As Integer Dim nMin As Integer Dim nSec As Integer If nTime > 3600 Then nTime = 3600 End If nSec = nTime Mod 60 nTime = (nTime - nSec) / 60 nMin = nTime Mod 60 nHour = (nTime - nMin) / 60 gvFireTime = Now + TimeSerial(nHour, nMin, nSec) Application.OnTime gvFireTime, "'HandleEvent TimerEvent, """"'" End Function ' タイマー取消 Function CancelTimer() Application.OnTime gvFireTime, "'HandleEvent TimerEvent, """"'", , False End Function ' 終了 Sub Quit() Dim vCode As Variant On Error GoTo E CancelTimer For Each vCode In gvKeyCodes Application.OnKey vCode Next E: End Sub