如果string是一个数字,则将vba转换为int [英] vba convert string to int if string is a number

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

问题描述

我需要将一个从Excel获得的字符串转换成VBA到一个整数。为了做到这一点,我使用的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。

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

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

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