Home » excel » excel – How do I set a dynamic array size in execution time?

excel – How do I set a dynamic array size in execution time?

Posted by: admin May 14, 2020 Leave a comment

Questions:

I’m removing duplicated strings from an array and I’m pretty sure I need to use the Redim statement to dynamically change the size of the array, but I can’t get it to work right.

Here’s what I tried:

Dim temp() as String
Dim vetOrg as Variant

vetOrg = Array(contRows)
ReDim vetOrg(1 To contRows)


'populates the array
For i = 1 To contRows
    vetOrg(i) = wsDeals.Cells(i + 1, 2).Value
Next i


 j = 1
    For i = 1 To contRows
        ReDim temp(1 To j)
        If vetOrg(i) <> vetOrg(i + 1) Then
            temp(j = j + 1) = vetOrg(i)
        End If
        temp(j = j + 1) = vetOrg(contRows - 1)
    Next i
How to&Answers:

With a Scripting.Dictionary you don’t need to worry about resizing or searching for duplicate values; dictionary keys are inherently unique:

Dim vetOrg As Scripting.Dictionary
Set vetOrg = New Scripting.Dictionary

For i = 1 To contRows
    vetOrg(wsDeals.Cells(i + 1, 2).Value) = i ' value is bogus, it's the key we want.
Next i

'done. vetOrg.Keys has the unique values.