I need to convert a string, obtained from excel, in VBA to an interger. To do so I'm using CInt()
which works well. However there is a chance that the string could be something other than a number, in this case I need to set the integer to 0. Currently I have:
If oXLSheet2.Cells(4, 6).Value <> "example string" Then currentLoad = CInt(oXLSheet2.Cells(4, 6).Value) Else currentLoad = 0 End If
The problem is that I cannot predict all possible non numeric strings which could be in this cell. Is there a way I can tell it to convert if it's an integer and set to 0 if not?
In Python an strings can be converted into a integer using the built-in int() function. The int() function takes in any python data type and converts it into a integer.
You convert a string to a number by calling the Parse or TryParse method found on numeric types ( int , long , double , and so on), or by using methods in the System. Convert class. It's slightly more efficient and straightforward to call a TryParse method (for example, int.
To convert, or cast, a string to an integer in Python, you use the int() built-in function. The function takes in as a parameter the initial string you want to convert, and returns the integer equivalent of the value you passed. The general syntax looks something like this: int("str") .
Use IsNumeric
. It returns true if it's a number or false otherwise.
Public Sub NumTest() On Error GoTo MyErrorHandler Dim myVar As Variant myVar = 11.2 'Or whatever Dim finalNumber As Integer If IsNumeric(myVar) Then finalNumber = CInt(myVar) Else finalNumber = 0 End If Exit Sub MyErrorHandler: MsgBox "NumTest" & vbCrLf & vbCrLf & "Err = " & Err.Number & _ vbCrLf & "Description: " & Err.Description End Sub
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With