• VBA Code to Disable Numlock

    Author
    Topic
    #353003

    I don’t like using Sendkeys. This is sometimes quite tricky. Here you have some code based on API calls that does the job.

    Option Explicit

    Private Type KeyboardBytes
    kbByte(0 To 255) As Byte
    End Type

    Dim kbArray As KeyboardBytes

    Private Declare Function GetKeyState Lib “user32” (ByVal nVirtKey As Long) As Long
    Private Declare Function GetKeyboardState Lib “user32” (kbArray As KeyboardBytes) As Long
    Private Declare Function SetKeyboardState Lib “user32” (kbArray As KeyboardBytes) As Long
    Const VK_NUMLOCK = &H90

    Private Function Get_Value() As Boolean
    Get_Value = GetKeyState(VK_NUMLOCK) And 1 = 1
    End Function

    Private Sub Set_Value(boolVal As Boolean)
    Call GetKeyboardState(kbArray)
    kbArray.kbByte(VK_NUMLOCK) = Abs(boolVal)
    Call SetKeyboardState(kbArray)
    End Sub

    Sub change_NUMLOCK()
    Dim State_Numlock As Boolean
    State_Numlock = Get_Value
    If State_Numlock = True Then
    Call Set_Value(False)
    Else
    Call Set_Value(True)
    End If
    End Sub

    With the Get_Value function, I read the numlock status. With the Set_Value subroutine I set the numlock status.
    In the change_NUMLOCK subroutine, I just toggle the numlock key.

    Viewing 1 reply thread
    Author
    Replies
    • #515043

      Thank you Hans!
      It works beautifully. I modified it slightly to always turn off numlock. I don’t understand the array of 255 values called keyboardbytes. But it sure works like a charm. Thanks So Much Again.

      • #515130

        You can find other keycodes in the winapi32.txt. (I think you can download this API information textfile from the microsoft website). I think 255 bytes were preserved for the keys on the keyboard. Here you have some others.
        Const VK_NUMLOCK = &H90
        Const VK_SHIFT As Integer = &H10
        Const VK_CONTROL As Integer = &H11
        Const VK_MENU As Integer = &H12 ‘Alt key
        Const VK_CAPSLOCK = &H14
        The GetKeyState API tells you whether a particular key is pressed. Suppose you want to know if the NUMLOCK key was pressed, then you call GetKeyState with the NUMLOCK constant as its argument.

    • #515016

      I am trying to write a macro that disables numlock upon opening an excel spreadsheet (that is primarily used on lap-tops). The following is what I am trying, but it doesn’t seem to be successful.

      Sub numlock()
      Application.SendKeys (“{NUMLOCK}”)
      End Sub

      Any suggestions would be appreciated. Thanks!!

    Viewing 1 reply thread
    Reply To: VBA Code to Disable Numlock

    You can use BBCodes to format your content.
    Your account can't use all available BBCodes, they will be stripped before saving.

    Your information: