Home > Net >  VBA Take specific values from one array into another array dynamically
VBA Take specific values from one array into another array dynamically

Time:10-07

I have an array with over 130 elements, out of those elements I only want specific elements. Those elements I have been able to specify with an if statement and an Instr function. However, I am stuck when figuring out how to those values from main array into a different array. The issue is that I don't know how many values will actually fit the requirements and so the second array I can't define before the values are counted.

How would I transfer certain values that fit the Instr function from one array to the other array.

Current code -

For v = 0 To UBound(NViews)

  ViewNames = NViews(v)
    If InStr(ViewNames, "Triage Folder") Then
    ReDim TriageNames(0 To p)
    TriageNames(p) = NViews(v)
    p = p   1
  End If

Next

Updated Code**

p = 1
ReDim TriageNames(0 To p)

For v = 0 To UBound(NViews)

ViewNames = NViews(v)
If InStr(ViewNames, "Triage Folder") Then

TriageNames(p) = NViews(v)
p = p   1

ReDim Preserve TriageNames(0 To p)

End If

Next

CodePudding user response:

Make TriageNames the same size as NViews, then use ReDim Preserve, after you populated TriageNames completely:

Dim TriageNames As Variant
ReDim TriageNames(0 to Ubound(NViews))

For v = 0 To Ubound(NViews)
   If InStr(NViews(v), "Triage Folder") > 0 Then
       Dim p As Long
       TriageNames(p) = NViews(v)
       p = p   1
   End If
Next

If p > 0 Then
   ReDim Preserve TriageNames(0 to p - 1)
End If
  • Related