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)
强制转换为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)。更改函数返回类型,并重命名所有出现的函数变量以使所有内容保持一致。