【问题标题】:Add cell address to an array when cell value = 0 VBA当单元格值 = 0 VBA 时将单元格地址添加到数组
【发布时间】:2020-12-01 19:24:13
【问题描述】:

我有一个 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

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

【问题讨论】:

  • 您的意思是向二维数组或一维数组添加零?
  • 我认为由于重用变量 i,我遇到了一些错误。请检查更正后的代码。
  • 太棒了。感谢您的更新。

标签: arrays excel vba loops


【解决方案1】:

你可以这样做:

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

【讨论】:

  • 您在 For ... Next 循环中有 i = i + 1 也使用 i。这不会影响循环的工作吗?
  • 嘿 Tarik,这看起来不错但很快的问题,我如何才能使用我创建的数组引用特定单元格,以便我可以返回并修改它?例如:如果我放了一个 if 语句,如果当前单元格值 = 6,我需要回到我从 0 修改的最后一个单元格。我将编辑代码以显示。
  • 查看修改后的解决方案,该解决方案存储范围而不是地址,应该可以完成这项工作。
  • 旁注:认为您知道在像Dim i, j, k as Integer 这样的声明中,只有k 获得Integer 数据类型,ij 将是Variants 如果未声明明确@Tarik
  • 不客气。 - 与 OP 中类似:Dim i As Integer, j As Integer, k as Integer;我更喜欢As Long,尤其是对于更高的计数器,并且由于内部 VBA 恢复为Long@Tarik
【解决方案2】:

请试试这个功能。它返回计数和地址字符串。它采用的参数之一是要替换找到的零的值。

Private Sub Test_CountSeroes()
    Dim Addresses() As String
    MsgBox CountZeroes("Replaced", Addresses)
    Debug.Print Join(Addresses, ",")
End Sub

Function CountZeroes(ByVal x As Variant, _
                     Fun() As String) As Long

    Const CountRange    As String = "B2:H13"    ' change to suit
    
    Dim Rng             As Range                ' = CountRange
    Dim Cell            As Range                ' loop counter: cells
    Dim i               As Long                 ' index of Fun()
    
    Set Rng = Range(CountRange)
    ReDim Fun(1 To Rng.Count)
    For Each Cell In Rng
        With Cell
            If .Value = 0 Then
                .Value = x
                i = i + 1
                Fun(i) = .Address(0, 0)
            End If
        End With
    Next Cell
    If i Then ReDim Preserve Fun(1 To i)
    CountZeroes = i
End Function

【讨论】:

    猜你喜欢
    • 2020-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-27
    • 1970-01-01
    • 2015-10-09
    相关资源
    最近更新 更多