WoeIs
WoeIs

Reputation: 1083

My VBA code for a textbox does not include the final input in the cell value

Private Sub TextBox1_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
    Worksheets("Sheet1").Range("A1").Value = TextBox1.Value
    If Not (KeyAscii >= 48 And KeyAscii <= 57) Then
        KeyAscii = 0
        MsgBox "Digits only"
    End If
End Sub

Code is used on a textbox in a userform.

I received some help yesterday and got this helpful piece of VBA code which works nicely. However, there is a slight bug with this. The textbox is supposed to only accept digits (hence the KeyAscii >= 48 And KeyAscii <= 57) however the last input digit does not get converted to the cell.

For instance, when you type "1234" in the textbox, it only writes "123" in the cell and omits the last digit.

Upvotes: 0

Views: 201

Answers (1)

JNevill
JNevill

Reputation: 50019

This subroutine is being activated upon the keypress, so they key hasn't registered as a entry into the textbox yet.

You can concatenate the last character (keypress character) onto your cell value though:

Private Sub TextBox1_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
    Worksheets("Sheet1").Range("A1").Value = TextBox1.Value & chr(KeyAscii)
    If Not (KeyAscii >= 48 And KeyAscii <= 57) Then
        KeyAscii = 0
        MsgBox "Digits only"
    End If
End Sub

Upvotes: 4

Related Questions