首页 > 解决方案 > 当单元格值 = 0 VBA 时将单元格地址添加到数组

问题描述

我有一个 for 循环遍历的单元格范围。如果有一个单元格中包含 0,则更改为某个数字并将单元格地址保存到数组中?

我不确定有多少单元格一开始就会有 0。

下面是我希望它如何工作的伪代码

For i = 1 to 9
     For j = 1 to 9
         if cell.value = 0 then
            cell.value = x
            '''Add cell.address to array'''
         End if
     next j
next i

编辑:感谢大家的帮助。现在我可以引用将地址添加到数组中,有没有办法根据需要返回地址?我希望能够引用我修改的最后一个单元格,就像在三个块引号中看到的那样:

For i = 1 to 9
         For j = 1 to 9
             if cell.value = 0 then
                cell.value = x
                nums(n) = cell.adress
              n = n+1
             Elseif cell.value = y
           """Return back to the last cell added to the array, and put x+1"""
             End if
         next j
 next i

如果我需要提出另一个问题,我可以。

标签: arraysexcelvbaloops

解决方案


你可以这样做:

Dim ranges(81) ' Enough to hold 9x9 ranges
Dim i As Integer
Dim j As Integer
Dim k As Integer
k = 1
For i = 1 to 9
     For j = 1 to 9
         If cell.value = 0 then
            cell.value = x
            Set ranges(k) = cell
            k = k + 1
         ElseIf k>1 Then
            Set ranges(k-1).Value = x+1
         End if
     next j
next i

推荐阅读