如果string是数字,则vba将字符串转换为int

Cap*_*tic 59 excel vba excel-vba

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

If oXLSheet2.Cells(4, 6).Value <> "example string" Then
  currentLoad = CInt(oXLSheet2.Cells(4, 6).Value)
Else
  currentLoad = 0
End If
Run Code Online (Sandbox Code Playgroud)

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

For*_*oop 95

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

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
Run Code Online (Sandbox Code Playgroud)

  • 作为使用IsNumeric的替代方法,您可以简单地以默认值零开始,尝试使用Int转换提供的值,并忽略任何错误,如下所示:`Public Function IntOrZero(ByVal vValue As Variant)As Double | IntOrZero = 0 | On Error Resume Next | IntOrZero = Int(vValue)| End Function` - 只需替换| 有换行符. (4认同)
  • 即使IsNumeric返回True,CInt仍可能因溢出而失败 - 特别是对于小于-32768或大于32767的数字. (3认同)
  • 如果您遇到溢出,请使用 Long 数据类型和 `CLng(expression)` 转换为 Long,而不是 Int。 (2认同)

Pet*_*erH 7

强制转换为long或强制转换为int,请注意以下几点。

这些功能是Excel VBA中的视图功能之一,取决于系统区域设置。因此,如果您像在欧洲某些国家/地区那样在双引号中使用逗号,则会在美国遇到错误。

例如,在欧洲的excel版本0,5中,使用CDbl()的效果很好,但是在美国的版本中,结果为5。因此,我建议使用以下替代方法:

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
Run Code Online (Sandbox Code Playgroud)

当然,您也可以考虑人们使用逗号和点的情况,例如,三千作为3,000.00。如果您需要针对此类情况的功能,则必须检查其他解决方案。


小智 5

试试这个: currentLoad = ConvertToLongInteger(oXLSheet2.Cells(4, 6).Value) 使用这个函数:

Function ConvertToLongInteger(ByVal stValue As String) As Long
 On Error GoTo ConversionFailureHandler
 ConvertToLongInteger = CLng(stValue)  'TRY to convert to an Integer value
 Exit Function           'If we reach this point, then we succeeded so exit

ConversionFailureHandler:
 'IF we've reached this point, then we did not succeed in conversion
 'If the error is type-mismatch, clear the error and return numeric 0 from the function
 'Otherwise, disable the error handler, and re-run the code to allow the system to 
 'display the error
 If Err.Number = 13 Then 'error # 13 is Type mismatch
      Err.Clear
      ConvertToLongInteger = 0
      Exit Function
 Else
      On Error GoTo 0
      Resume
 End If
End Function
Run Code Online (Sandbox Code Playgroud)

我选择 Long (Integer) 而不是简单的 Integer,因为 VBA 中 Integer 的最小/最大大小很糟糕(最小值:-32768,最大值:+32767)。在电子表格操作中,整数超出该范围是很常见的。

可以修改上面的代码来处理从字符串到整数、到货币(使用 CCur() )、到小数(使用 CDec() )、到双精度(使用 CDbl() )等的转换。只需替换转换函数本身(CLng)。更改函数返回类型,并重命名所有出现的函数变量以使所有内容保持一致。