First, maybe you could force them to only type numbers.
Second, I misread your post. I thought you had multiple textboxes to check.
This kind of thing will work with a single box, though.
Third. The value in the textbox will be text. But when you plop into a cell,
excel will see it as a number. You can either format that cell (custom 000000)
to show leading 0's or precede the value with an apostrophe (or even preformat
the cell as text).
Fourth, this seemed to work ok:
Option Explicit
Private Sub CommandButton1_Click()
Unload Me
End Sub
Private Sub CommandButton2_Click()
Dim DestCell As Range
Dim iCtr As Long
Set DestCell = Worksheets("sheet1").Range("a1")
For iCtr = 1 To 2
With DestCell.Offset(0, iCtr - 1)
.Value = Me.Controls("textbox" & iCtr).Value
.NumberFormat = "000000"
End With
Next iCtr
Unload Me
End Sub
Private Sub TextBox1_Exit(ByVal Cancel As MSForms.ReturnBoolean)
With Me.TextBox1
.Value = Format(.Value, "000000")
End With
End Sub
Private Sub TextBox2_Exit(ByVal Cancel As MSForms.ReturnBoolean)
With Me.TextBox2
.Value = Format(.Value, "000000")
End With
End Sub
Private Sub TextBox1_KeyPress(ByVal _
KeyAscii As MSForms.ReturnInteger)
Call ValidateTextBoxes(Me.TextBox1, KeyAscii)
End Sub
Private Sub TextBox2_KeyPress(ByVal _
KeyAscii As MSForms.ReturnInteger)
Call ValidateTextBoxes(Me.TextBox2, KeyAscii)
End Sub
Sub ValidateTextBoxes(tb As MSForms.TextBox, KeyAscii As MSForms.ReturnInteger)
With tb
If Len(.Value) < 6 Then
Select Case KeyAscii
Case 8 'backspace
If Len(.Value) 0 Then
.Value = Left(.Value, Len(.Value) - 1)
End If
Case 48 To 57
Case Else
KeyAscii = 0
End Select
Else
KeyAscii = 0
End If
End With
End Sub
=======
and here's the code cleaned up for just one textbox:
Option Explicit
Private Sub CommandButton1_Click()
Unload Me
End Sub
Private Sub CommandButton2_Click()
Dim DestCell As Range
Set DestCell = Worksheets("sheet1").Range("a1")
With DestCell
.Value = Me.TextBox1.Value
.NumberFormat = "000000"
End With
Unload Me
End Sub
Private Sub TextBox1_Exit(ByVal Cancel As MSForms.ReturnBoolean)
With Me.TextBox1
.Value = Format(.Value, "000000")
End With
End Sub
Private Sub TextBox1_KeyPress(ByVal _
KeyAscii As MSForms.ReturnInteger)
With Me.TextBox1
If Len(.Value) < 6 Then
Select Case KeyAscii
Case 8 'backspace
If Len(.Value) 0 Then
.Value = Left(.Value, Len(.Value) - 1)
End If
Case 48 To 57
Case Else
KeyAscii = 0
End Select
Else
KeyAscii = 0
End If
End With
End Sub
Kev wrote:
I have a user form with a text box that I want only to
accept numbers with 6 digits.
How do you format text box to accept only numbers - which
can have preceding zeros? Can this format be carried
through to the worksheet where these numbers will be
stored?
How do you alert the user, prior to them moving onto the
other text boxes on the user form, that they have not
entered valid data and should reenter the data?
Thanks a million,
Kev.
--
Dave Peterson
|