Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert any Cell into an Integer if possible in VBA for Excel?

I would like to create a function that will take as a parameter a Cell and return an Integer. If the conversion is not successful it should simply return 0, without throwing error messages to the user.

I don't care about the cells that contain float values, they could also return 0 since it doesn't look like integer. But text values like 00001234 should return 1234 and 12 34 should return 0.

like image 944
Lipis Avatar asked Oct 15 '25 15:10

Lipis


1 Answers

How about this:

Option Explicit

Public Function ConvertToInteger(Cell As Range) As Integer
   On Error GoTo NOT_AN_INTEGER
   ConvertToInteger = CInt(Cell.Value)
   Exit Function
NOT_AN_INTEGER:
   ConvertToInteger = 0
End Function

Note, for example, that a value of 5.6 will return 6, though. If you want it to be 0 instead, you must check for it and do accordingly.

like image 74
Oneide Avatar answered Oct 18 '25 09:10

Oneide