当前位置: 主页 > Office办公 > Excel专区 > Excel函数 > 如何用VBA检查Caps Lock键是否打开

如何用VBA检查Caps Lock键是否打开

  • 2023-02-25
  • 来源/作者: Wps Office教程网/ 菜鸟图库
  • 160 次浏览

要用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