Convert string to int if string is a number

前端 未结 6 1144
余生分开走
余生分开走 2020-12-05 06:08

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

6条回答
  •  被撕碎了的回忆
    2020-12-05 06:33

    Cast to long or cast to int, be aware of the following.

    These functions are one of the view functions in Excel VBA that are depending on the system regional settings. So if you use a comma in your double like in some countries in Europe, you will experience an error in the US.

    E.g., in european excel-version 0,5 will perform well with CDbl(), but in US-version it will result in 5. So I recommend to use the following alternative:

    Public Function CastLong(var As Variant)
    
        ' replace , by .
        var = Replace(var, ",", ".")        
    
        Dim l As Long
        On Error Resume Next
        l = Round(Val(var))
    
        ' if error occurs, l will be 0
        CastLong = l
    
    End Function
    
    ' similar function for cast-int, you can add minimum and maximum value if you like
    ' to prevent that value is too high or too low.
    Public Function CastInt(var As Variant)
    
        ' replace , by .
        var = Replace(var, ",", ".")
    
        Dim i As Integer
        On Error Resume Next
        i = Round(Val(var))
    
        ' if error occurs, i will be 0
        CastInt = i
    
    End Function
    

    Of course you can also think of cases where people use commas and dots, e.g., three-thousand as 3,000.00. If you require functionality for these kind of cases, then you have to check for another solution.

提交回复
热议问题