excel - 在 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
解决方案
你必须首先维度一个数组
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
因为它可以防止在向其中添加项目时重新初始化数组的内容。
推荐阅读
- python - 从 set python 中删除第一个重复项并仅保留最后一个唯一的
- java - 如何在 android 中将 zip 文件上传和下载到谷歌驱动器?
- sql - 在第一次出现符号之前从字符串中提取文本
- flutter - 如何在 Flutter 的小部件树中将新的 MaterialPageRoute 作为子项打开
- angular - Angular 9:一种形式的多个 ngb-typeahead?
- php - 添加两个多维 PHP 关联数组
- android - Android Room - 定义 Room 表名、ColumnInfo 等时无法解析方法/符号
- angular - Angular 9:无法通过依赖注入创建该类,因为它没有 Angular 装饰器
- spring - 我可以将 CircleCI 中的环境变量传递给 Spring Boot 中的代码吗?
- snowflake-cloud-data-platform - ServiceNow 连接到雪花