如何使用IF语句循环遍历工作表,并将每个语句TRUE附加到数组中?
基本示例,如果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
Run Code Online (Sandbox Code Playgroud)
您必须首先确定数组的尺寸
Dim myArray() as Integer
Run Code Online (Sandbox Code Playgroud)
在循环内,跟踪数组将具有的元素数量
Dim myCount as Integer
Run Code Online (Sandbox Code Playgroud)
然后在循环中,您必须增加此计数器并重新调整数组的大小,以便可以添加到它
If Cells(y, 1).Value > 0 Then
myCount=myCount+1
Redim Preserve myArray(1 to myCount)
myArray(myCount)=1
Run Code Online (Sandbox Code Playgroud)
保留Preserve字很重要,因为它可以防止在向数组添加项目时重新初始化数组的内容。
| 归档时间: |
|
| 查看次数: |
5543 次 |
| 最近记录: |