0

How to update each item of a Boolean array in a For... Each loop?

This code updates item variable in every loop but it doesn't update the array items themselves.

Dim BoolArr(1 to 4) as Boolean
Dim item as Variant
For Each item in BoolArr
    item = True
Next

Dim t as Long
Dim str as String
For t = Lbound(BoolArr) to Ubound(BoolArr)
 str = str & CStr(BoolArr(t))
Next t
Debug.Print str

Shows "FalseFalseFalseFalse".

On the other hand, this For .. To .. loop DOES update array items:

Dim BoolArr(1 to 4) as Boolean
Dim n as Long
For n = Lbound(BoolArr) to Ubound(BoolArr)
    BoolArr(n) = True
Next

Dim t as Long
Dim str as String
For t = Lbound(BoolArr) to Ubound(BoolArr)
 str = str & CStr(BoolArr(t))
Next t
Debug.Print str

Shows "TrueTrueTrueTrue".

How to correct the For Each loop so that it updates array items?


It is a duplication of VBA - Update values in an array with For Each statement

7
  • 1
    item is a throwaway variable that contains a copy of (eg) BoolArr[t]. Setting item to something is not the same as setting BoolArr[t] to something. Commented Aug 12, 2024 at 20:57
  • @James Yes, the difference is observed. Is item linked to array items anyway, so updating item updates the array itself? In contrast, one can update values of cells within a range with For Each loop: learn.microsoft.com/en-us/office/vba/language/concepts/… Commented Aug 12, 2024 at 21:05
  • updating item updates the array no you can’t - the variable item is completely separate to the array. If you want to replace an array element use a regular for loop with an index. Commented Aug 13, 2024 at 2:59
  • Use For loop when iterating an array. Use For Each loop when iterating an object (like a collection, or a range). Commented Aug 13, 2024 at 9:26
  • 1
    Note that "item as a copy" depends on the type of the array. Since booleans are value types, the variable is always a copy. For reference items, you have a copy of the reference... which may still refer to the same object as the reference in the array. Commented Aug 13, 2024 at 16:38

0

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.