I was looking here for the answer to my problem but still, do not know how to solve it so I am refreshing the topic.
I have a primitive function that searches in the Worksheet (column A) the inputs to Userform.TextBox1
, UserForm.Textbox2
, etc. When a particular record is found, it should assign to an array the record itself and values from next 3 or 4 cells from the same row (each row ends with “End”). In this way, I will have the array of max 4 columns and as many rows as records will be found
The first Do
loop goes perfect but increasing the size
variable (found records), so increasing the array’s row as I wanted, gives me the subscript out of range
error. I spent on this a whole day but I do not see what I am missing.
Here’s the code:
Sub test()
Dim arr() As Variant
Dim i, size As Integer
Dim back As String
Cells(1, 1).Select
i = 0
size = 0
Do Until ActiveCell.Value = UserForm1.TextBox1.Value
ActiveCell.Offset(1, 0).Select
Loop
back = ActiveCell.Address
Do Until ActiveCell = "End"
size = size + 1
ReDim Preserve arr(1 To size, 1 To 4)
Do Until ActiveCell.Value = "End"
i = i + 1
arr(size, i) = ActiveCell
ActiveCell.Offset(0, 1).Select
Loop
Loop
Range(back).Offset(1, 0).Select
Do Until ActiveCell.Value = UserForm1.TextBox2.Value
ActiveCell.Offset(1, 0).Select
Loop
back = ActiveCell.Address
i = 0
Do Until ActiveCell = "End"
size = size + 1
ReDim Preserve arr(1 To size, 1 To 4) '"Subscript out of range" error occurs here
Do Until ActiveCell.Value = "End"
i = i + 1
arr(size, i) = ActiveCell
ActiveCell.Offset(0, 1).Select
Loop
Loop
End Sub