PDA

View Full Version : String to Integer Conversion



maggie
07-22-2011, 03:04 PM
I am collecting values in a textbox in a UserForm.

I am then using these values in calculations, however if I leave a field blank it halts my calculation as a string default value is ("") rather than (0) as an integer is. How can do this conversion? I didn't think Dim as integer would work here as I am grabbing the data from a userform.

Thanks

gmaxey
07-22-2011, 04:44 PM
Have you tried VAL?

Private Sub CommandButton1_Click()
MsgBox Val(Me.TextBox1.Text) + Val(Me.TextBox2.Text)
End Sub

maggie
07-26-2011, 01:47 PM
Works! Thank you Greg

DanielHowden
07-27-2011, 12:37 AM
You could always do it like this-

Dim MyString As String
Dim MyInt As Integer

MyString = "99"
MyInt = Int(MyString)

Cheers Daniel.

gmaxey
07-27-2011, 04:38 PM
Sub WellNotAlways()
Dim MyString As String
Dim MyInt As Integer
MyString = "99"
MyInt = Int(MyString)
Debug.Print MyInt
'If the default string value of an empty textbox is "" as indicated by the OP then
MyString = ""
On Error GoTo Err_Handler
MyInt = Int(MyString)
Debug.Print MyInt
Exit Sub
Err_Handler:
If MyString = "" Then MyString = "0"
Resume
End Sub

Frosty
07-27-2011, 05:34 PM
Greg: Just need to edit to use the VBA tags and the joke would have been perfect.

My preference for dealing with conversion functions (although I love learning about Val), is to rewrite them better than microsoft did (so that they *always* convert to a default value, even on an error). So, for me, the CStr becomes fCStr, CSng becomes fCSng, with basically the same usage.

As important as Greg's point was (dealing with empty strings), equally important would be trusting that integer is a good enough type without more info from the original poster. If the user can input 2.4 into the text box... converting that to an integer is going to give you 2.

The following function would work in the following way:
fCSng("") = 0
fCSng("34") = 34
fCSng(Null) = 0
fCSng("4.3") = 4.3


'Convert any passed variable to a Single, default return on any error is 0
Public Function fCSng(var as Variant) As Single
On Error GoTo l_err
fCSng = CSng(var)
l_exit:
Exit Function
l_err:
fCng=0
Resume l_exit
End Function