首页 > 解决方案 > 在 Excel VBA Basic 中使用 for 循环追加到数组

问题描述

如何使用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

标签: excelvbaappend

解决方案


你必须首先维度一个数组

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因为它可以防止在向其中添加项目时重新初始化数组的内容。


推荐阅读