excel - 在 Excel VBA Basic 中使用 for 循环追加到数组

标签 excel vba append

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

相关文章:

Python:理解 append 和扩展之间的区别

c# - 在c#中处理大量excel工作簿时如何跳过一些受密码保护的excel文件

javascript - 如何使用javascript存储Excel文件

vba - 在 VBA 中无法从工作簿事件处理程序 Workbook_BeforeClose 或 Workbook_Deactivate() 调用工作表中的子例程

arrays - 加权中位数 - 数组的 UDF?

Python循环遍历列表并根据条件追加

jquery - 如何使用 jQuery append()(以正确的顺序)执行大量的 DOM 插入?

html - 从 HTML 中提取数据

Excel - 如何使用一个单元格的值作为另一个单元格的行值?

html - 从vba中的下拉框中选择各种选项