Log in

View Full Version : String to integer...not VAL()!



mud2
08-16-2009, 07:55 PM
What am I missing? There MUST be a function that returns the numerical value of a string! Val() only returns the imbedded (if any) number in the string.

CreganTur
08-17-2009, 05:10 AM
What you're looking for is called Casting- it allows you to treat a variable of one data type as a different data type. There are a number of different Casting functions. If you want to turn your string variable into an Integer, you would use:
CInt(strVar) '<<<Casts String variable strVar as an Integer

Lookup Type Casting in Access Help to see all the available methods.

If your string variable contains anything other than numbers, you could end up with unexpected results.

mud2
08-18-2009, 10:33 AM
I sent a "Thanks", but it's gone! Anyway, Cint only rounds an integer. I want to convert a string, eg. AV34Jk to an integer.
Guess I have ti do it the hard way:

Public Function Startme(ThisString) As Long
Dim length As Integer
Dim i, j As Integer
Dim thischar As String
Dim thisint As Long
Dim chars() As String
Dim ints() As Long
Dim expt As Integer
thisint = 0
length = Len(ThisString)
ReDim chars(1 To length)
ReDim ints(1 To length)
For i = 1 To length
expt = length - i
chars(i) = Mid(ThisString, i, 1)
ints(i) = Asc(chars(i)) - 47 ' just reduces size Don't use first 47

thisint = thisint + ints(i) * 10 ^ expt
Next i
Startme = thisint
End Function

Comments???

mud2
08-18-2009, 10:38 AM
Addendum: This method "works", but only for up to 8 alphanumeric characters...otherwise get an "out of range" for the returned integer. But I only use 8, so I just made it?
If you want to use all the ascii characters, don't subtract the "47".
I suppose "double" could be worked in for larger returns....