[VBA] Extracting array items into another array

Overside

New Member
Joined
Jul 24, 2018
Messages
4
In VBA I'm trying to generate an array (Array2) that takes values from another array (Array1) that meet a certain condition like the following code:

Code:
Dim j As Long
j = 0
For i = 0 To UBound(Array1)
    If Left(Array1(i), 4) = cnstVal Then
        ReDim Array2(j + 1)
        Array2(j) = Array1(i)
        j = j + 1
    End If
Next i

End Sub
Should be simple enough... however something weird happens when I run the code. At the end of the code execution Array2 is the correct size but all items are blank/empty. And as I'm debugging my code I checked that after each iteration of for loop Array2 actually has the correct item value being assigned to the correct index, but somehow once the code exits the loop all entries become blank??

I spent way too long on trying to understand this at no avail, although it's probably something stupid. Hopefully someone can blow my mind :confused:
 

Excel Facts

How to total the visible cells?
From the first blank cell below a filtered data set, press Alt+=. Instead of SUM, you will get SUBTOTAL(9,)
Every time you redim an array all the items in it are erased, to keep them use ReDim Preserve.
Code:
ReDim Preserve Array2(j+1)
 
Upvote 0

Forum statistics

Threads
1,224,836
Messages
6,181,252
Members
453,028
Latest member
letswriteafairytale

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top