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
itemis 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.itemlinked to array items anyway, so updatingitemupdates 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/…updating item updates the arrayno 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.