要用VBA代碼判斷Caps Lock鍵、Num Lock鍵及Scroll Lock鍵的開啟狀態,可以用下面的代碼,前四行代碼為API聲明,需放置在代碼窗口的最上方:
Private Declare Function GetKeyState Lib "user32" (ByVal nVirtKey As Long) As Integer
Const VK_NUMLOCK = &H90
Const VK_SCROLL = &H91
Const VK_CAPITAL = &H14
Private Sub KeyStates()
If GetKeyState(VK_CAPITAL) Then ‘Caps Lock鍵
MsgBox "Caps Lock ON"
Else
MsgBox "Caps Lock OFF"
End If
If GetKeyState(VK_NUMLOCK) Then ‘Num Lock鍵
MsgBox "Num Lock ON"
Else
MsgBox "Num Lock OFF"
End If
If GetKeyState(VK_SCROLL) Then ‘Scroll Lock鍵
MsgBox "Scroll Lock ON"
Else
MsgBox "Scroll Lock OFF"
End If
End Sub
另外,在Word中可以使用下面的VBA代碼來判斷Caps Lock鍵是否開啟:
Sub KeyStates()
If Selection.Information(wdCapsLock) Then
MsgBox "Caps Lock 鍵已開啟"
Else
MsgBox "Caps Lock 鍵已關閉"
End If
End Sub