none
OnKeyPress event is not working properly when using a function RRS feed

  • Question

  • Hi All

    I am trying to make a common function to check for decimal values. If I keep the code inside even call, it works fine but if I move to a function and call the function from event procedure its not working. If I type any letter it wont be added in the text field in first case but adding in second case. Could you please help to rectify this error? Please see the code as below.

    Private Sub txtFdxStd_KeyPress(KeyAscii As Integer)
        CheckForDecimalsOnKeyPress (KeyAscii)
    End Sub

    ******

    Public Function CheckForDecimalsOnKeyPress(KeyAscii As Integer) As Integer
        If (KeyAscii > 47 And KeyAscii < 58) Or (KeyAscii = 8) Or (KeyAscii = 46) Then
           KeyAscii = KeyAscii
           Else:
           KeyAscii = 0
           MsgBox ("You Must Enter Numbers Only!")
        End If
    End Function

    Thank you very much in advance

    Jose

    Wednesday, October 26, 2016 9:04 PM

All replies

  • Hi All

    I am trying to make a common function to check for decimal values. If I keep the code inside even call, it works fine but if I move to a function and call the function from event procedure its not working. If I type any letter it wont be added in the text field in first case but adding in second case. Could you please help to rectify this error? Please see the code as below.

    Private Sub txtFdxStd_KeyPress(KeyAscii As Integer)
        CheckForDecimalsOnKeyPress (KeyAscii)
    End Sub

    ******

    Public Function CheckForDecimalsOnKeyPress(KeyAscii As Integer) As Integer
        If (KeyAscii > 47 And KeyAscii < 58) Or (KeyAscii = 8) Or (KeyAscii = 46) Then
           KeyAscii = KeyAscii
           Else:
           KeyAscii = 0
           MsgBox ("You Must Enter Numbers Only!")
        End If
    End Function

    Remove the parenthese around KeyAscii in the call to CheckForDecimalsOnKeyPress.  Instead of this:

        CheckForDecimalsOnKeyPress (KeyAscii)

    write this:

        CheckForDecimalsOnKeyPress KeyAscii

    If you put parentheses around the variable name when they aren't required (as in this case), you cause the variable name to be evaluated and the result of that evaluation to be passed to the function in its place.

    By the way, I don't see the point of the line

        KeyAscii = KeyAscii

    in CheckForDecimalsOnKeyPress.  Why don't you just write:

    Public Function CheckForDecimalsOnKeyPress(ByRef KeyAscii As Integer) As Integer
    
        If (KeyAscii > 47 And KeyAscii < 58) Or (KeyAscii = 8) Or (KeyAscii = 46) Then
            ' The key is okay, so leave it alone.
        Else
            KeyAscii = 0
            MsgBox ("You Must Enter Numbers Only!")
        End If
        
    End Function
    


    Dirk Goldgar, MS Access MVP
    Access tips: www.datagnostics.com/tips.html

    Wednesday, October 26, 2016 9:37 PM