I have a cell containing something like "12_34_56"
I used:
MyNumbers = Split(Cells(1, 1).Value, "_")
to split the numeric values into an array , but the result is an array of strings!
I know that I can use CInt on every value of the array but isn't any way to obtain a numeric array directly?
thanks in advance
As far as I'm aware it's not possible to convert one type of array into another type with a single call, but if you're going to be doing this conversion in multiple locations the obvious option is to write a function that returns the desired result, as below:
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
When you need this functionality you can just call this function as a one-liner as you would the Split function.
Dim arrMyInts() As Integer
arrMyInts = SplitIntegers(Cells(1,1).Value, "_")
This worked great for me and was very easy to set up! I will use cell A1 as the example with the string of numbers.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.