What I have
Let's take an example of this code which works.
Sub Sample()
Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets("Sheet1")
ws.Columns(1).TextToColumns _
Destination:=Range("A1"), _
DataType:=xlFixedWidth, _
FieldInfo:=Array( _
Array(0, 1), Array(60, 1), Array(120, 1), Array(180, 1), _
Array(240, 1), Array(300, 1), Array(360, 1), Array(420, 1) _
), _
TrailingMinusNumbers:=True
End Sub
What I want
In a small set of data, the above code works. But what if I want to go up to say Array(2700,1)
? This means I will have to write it 46
times Array(0, 1), Array(60, 1)...Array(1080, 1)....Array(2700, 1)
What I have tried
I tried using this approach
Sub Sample()
Dim ws As Worksheet
Dim MyArray
Dim MyStr As String
Dim i As Long
For i = 0 To 2700 Step 60
MyStr = MyStr & "#" & "Array(" & i & ",1)"
Next i
MyStr = Mid(MyStr, 2)
MyArray = Split(MyStr, "#")
Set ws = ThisWorkbook.Sheets("Sheet1")
ws.Columns(1).TextToColumns _
Destination:=Range("A1"), _
DataType:=xlFixedWidth, _
FieldInfo:=MyArray, _
TrailingMinusNumbers:=True
End Sub
Obviously that won't work as Array(i,1)
is stored as a string in MyArray
.
My Question
Is there any way we can create such kind of jagged arrays in a loop so that all I have to do is say FieldInfo:=MyArray
Does an array stored inside a jagged array need to be of the same type? for example can I store an array of ints and an array of strings in one jagged array? No, you may not do that.
A jagged array is an array whose elements are arrays, possibly of different sizes. A jagged array is sometimes called an "array of arrays." The following examples show how to declare, initialize, and access jagged arrays.
Jagged array is a multidimensional array where member arrays are of different size. For example, we can create a 2D array where first array is of 3 elements, and is of 4 elements. Following is the example demonstrating the concept of jagged array.
Jagged arrays are a special type of arrays that can be used to store rows of data of varying lengths to improve performance when working with multi-dimensional arrays.
You can assign an array to an array item like so:
Dim n As Long
n = 0
ReDim MyArray(2700 \ 60)
For i = 0 To 2700 Step 60
MyArray(n) = Array(i, 1)
n = n + 1
Next i
You are going correct. Instead of adding to string in loop, just create actual array items.
So this is what you will have:
Sub Sample()
Dim ws As Worksheet
Dim MyArray(20) As Variant '<-- specify the number of items you want
Dim i As Long
For i = 0 To UBound(MyArray)
MyArray(i) = Array(i * 60, 1)
Next
Set ws = ThisWorkbook.Sheets("Sheet1")
ws.Columns(1).TextToColumns _
Destination:=Range("A1"), _
DataType:=xlFixedWidth, _
FieldInfo:=MyArray, _
TrailingMinusNumbers:=True
End Sub
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With