如何在VBA的For Each循环中更新Boolean数组的元素?
如何在VBA的For Each循环中更新Boolean数组元素
在VBA里直接用For Each遍历Boolean数组时,修改循环变量item只会改变变量本身,并不会同步更新数组里的元素,比如下面的代码最终会输出FalseFalseFalseFalse:
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
而用For..To..循环通过索引访问数组元素,就能成功修改数组值,最终输出TrueTrueTrueTrue:
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
修正For Each循环的方法
VBA的For Each对Boolean这类值类型的数组遍历是按值传递的,循环变量item只是原数组元素的副本,修改它不会影响原数组。要实现用For Each修改数组元素,需要把值类型转为引用类型,具体可以通过自定义类包装Boolean值:
- 新建一个类模块,命名为
BoolWrapper,在类中添加代码:
Public Value As Boolean
- 在标准模块中创建这个类的数组,初始化后用
For Each遍历修改:
' 创建包装类数组并初始化实例 Dim BoolArr(1 To 4) As BoolWrapper Dim i As Long For i = LBound(BoolArr) To UBound(BoolArr) Set BoolArr(i) = New BoolWrapper Next i ' 用For Each修改元素值 Dim item As BoolWrapper For Each item In BoolArr item.Value = True Next ' 验证输出结果 Dim t As Long Dim str As String For t = LBound(BoolArr) To UBound(BoolArr) str = str & CStr(BoolArr(t).Value) Next t Debug.Print str ' 输出TrueTrueTrueTrue
如果不想额外创建类模块,最直接高效的方式还是使用For..To..索引循环,它不需要额外封装,性能也更优。
内容的提问来源于stack exchange,提问作者house_of_codes
相关产品推荐
相关产品推荐

