Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string to int if string is a number

Tags:

excel

vba

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?

like image 760
Captastic Avatar asked Jun 01 '11 13:06

Captastic


People also ask

Can you convert strings to ints?

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.

How do I convert a string to a number?

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.

How do I convert a string to an integer in Python?

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") .


1 Answers

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 
like image 175
ForEachLoop Avatar answered Sep 19 '22 06:09

ForEachLoop