Convert string to int if string is a number

前端 未结 6 1119
余生分开走
余生分开走 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:57

    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
    

提交回复
热议问题