如果字符串是数字,则将字符串转换为整数 [英] Convert string to int if string is a number

查看:131
本文介绍了如果字符串是数字,则将字符串转换为整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将VBA中从excel获得的字符串转换为整数.为此,我使用了效果很好的CInt().但是,字符串有可能不是数字,在这种情况下,我需要将整数设置为0.目前,我有:

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

问题是我无法预测此单元格中可能存在的所有可能的非数字字符串.有没有一种方法可以告诉我将其转换为整数,如果不是则设置为0?

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?

推荐答案

使用IsNumeric.如果是数字,则返回true;否则,返回false.

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

这篇关于如果字符串是数字,则将字符串转换为整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆