1

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
3
  • 3
    if you want to keep the values in the array, you need to use redim preserve ... otherwise please detail what you think is not working. also temp(j = j + 1) wont work... make j = j +1 before that and then do temp(j). Commented May 24, 2019 at 20:32
  • maybe interest codereview.stackexchange.com/questions/215646/… Commented May 24, 2019 at 21:15
  • 3
    You want to use a Dictionary instead; dictionary keys are inherently unique, and I'm pretty sure it's a O(1) hash lookup to determine whether a key exists - compared to O(n) for every element you lookup in an array. You'll want to reference the Microsoft Scripting Runtime library. Commented May 24, 2019 at 21:18

1 Answer 1

2

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.
Sign up to request clarification or add additional context in comments.

2 Comments

Hey thanks, but how do I debug.print this array? Since now I don't know its size. I tried LBound(vetOrg) - UBound(vetOrg) but it do not seems to work.
@Daniel you can't print an array, you need to iterate it and print its elements.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.