Text Box Format

G

gregork

I have a textbox on a user form that displays data from a worksheet. How can
I format the text box so that it only displays a number to 2 decimal places?

Cheers
Greg
 
R

Robert Bradshaw

gregork said:
I have a textbox on a user form that displays data from a worksheet. How can
I format the text box so that it only displays a number to 2 decimal places?

Cheers
Greg
or in the lostfocus code for the textbox:

Private Sub TextBox1_LostFocus()
TextBox1.Value = Round(TextBox1.Value, 2)
End Sub
 
G

gregork

Thanks for the help guys. I have used Robert's code and it works fine except
for when the text box value = "", then I get a type mismatch error. Any
suggestions how to prevent this from happening?

Regards
Greg
 
D

Dave Peterson

How about something like:

Option Explicit
Private Sub TextBox1_Exit(ByVal Cancel As MSForms.ReturnBoolean)
With Me.TextBox1
If IsNumeric(.Value) Then
.Value = Round(.Value, 2)
Else
.Value = "Numeric Please"
.SelStart = 0
.SelLength = Len(.Value)
Beep
Cancel = True
End If
End With
End Sub
 
G

gregork

Thanks Dave. Problem solved.

Cheers
Greg

Dave Peterson said:
How about something like:

Option Explicit
Private Sub TextBox1_Exit(ByVal Cancel As MSForms.ReturnBoolean)
With Me.TextBox1
If IsNumeric(.Value) Then
.Value = Round(.Value, 2)
Else
.Value = "Numeric Please"
.SelStart = 0
.SelLength = Len(.Value)
Beep
Cancel = True
End If
End With
End Sub
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top