如何使用 IF
语句循环遍历工作表,并将每个 TRUE
append 到数组中?
基本示例,如果 Cells(y, 1).Value
大于 0,则将 1 追加到数组中,并通过给定范围执行此操作,创建一个具有多个值 1 的数组(给定多个 Cells(y, 1).Value(s) 大于 0)。
这就是我之前创建循环的方式。
For y = 2 To LastRow
On Error Resume Next
If Cells(y, 1).Value > 0 Then
Cells(y, 2).Value = 1 ' Instead of populating Cells(y,2) with "1" IF true, I want to append the value to an array
ElseIf Cells(y, 1).Value = 0 > 0 Then
Cells(y, 2).Value = 2
Else
Cells(y, 2).Value = 0
End If
Next y
最佳答案
您必须首先确定数组的尺寸
Dim myArray() as Integer
在循环内,跟踪数组将拥有的元素数量
Dim myCount as Integer
然后在循环中,您必须增加此计数器并重新调整数组的大小,以便可以添加到其中
If Cells(y, 1).Value > 0 Then
myCount=myCount+1
Redim Preserve myArray(1 to myCount)
myArray(myCount)=1
Preserve
保留字很重要,因为它可以防止在向数组添加项目时重新初始化数组的内容。
关于excel - 在 Excel VBA Basic 中使用 for 循环追加到数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58548830/