我有一个包含“12_34_56”
之类的单元格我用过:
MyNumbers = Split(Cells(1, 1).Value, "_")
将数值拆分为数组,但结果是一个字符串数组!
我知道我可以在数组的每个值上使用CInt但是不能直接获取数值数组吗?
提前致谢
答案 0 :(得分:1)
据我所知,只有一次通话无法将一种类型的数据转换为另一种类型,但如果您要在多个位置进行此转换,显而易见的选择是编写一个返回所需结果的函数,如下所示:
Public Function SplitIntegers(StringToSplit As String, Sep As String) As Variant
Dim arrStrings() As String
Dim arrIntegers() As Integer
Dim i As Long
On Error GoTo Err_SplitIntegers
arrStrings = Split(StringToSplit, Sep)
ReDim arrIntegers(LBound(arrStrings) To UBound(arrStrings))
For i = LBound(arrStrings) To UBound(arrStrings)
arrIntegers(i) = CInt(arrStrings(i))
Next i
SplitIntegers = arrIntegers
Exit Function
Err_SplitIntegers:
Select Case Err.Number
Case 13 'Type Mismatch Error: StringToSplit contains non-numeric substrings
On Error GoTo 0
Err.Raise 9114, "SplitIntegers", _
"SplitIntegers failed: substring '" & arrStrings(i) & "' of string '" & StringToSplit & "' is not numeric"
Case Else 'Unhandled error, return to calling code
Dim iErrNum As Integer, strErrDesc As String
iErrNum = Err.Number
strErrDesc = Err.Description
On Error GoTo 0
Err.Raise iErrNum, "SplitIntegers", strErrDesc
End Select
End Function
当您需要此功能时,您可以将此功能称为单行,就像拆分功能一样。
Dim arrMyInts() As Integer
arrMyInts = SplitIntegers(Cells(1,1).Value, "_")
答案 1 :(得分:1)
这对我很有用,而且很容易设置!我将使用单元格A1作为带有数字字符串的示例。
Dim strarray as Variant
Dim intarray as Variant
Dim x as Long
strarray = Split(Range("A1").Value, "_")
ReDim intarray(LBound(strarray) to UBound(strarray))
For x = LBound(strarray) To UBound(strarray)
intarray(x) = CInt(strarray(x))
Next x