首页 > 解决方案 > For循环捕获不同命名范围内的值

问题描述

我一直在浏览多个有关循环多个命名范围并将值返回到另一个单元格的帖子。不幸的是,如果另一个命名范围中的单元格是“X”,我陷入了如何遍历两个命名范围以从一个命名范围返回值的问题。

下面是单元格 I46 中带有值和预期结果的命名范围的图像。请注意,I46 中没有公式。


命名范围:
Range1 Range2

要循环的命名范围

宏循环完成后的预期结果:
结果

代码:

    For Each Cell In wspGen.Range("Ineligible")
    If Cell.Value = vbNullString Then
        LP.zPledge.Value = "Y"
        wspGen.Range("A46") = "-"
        wspGen.Range("AG55").Value = "X"
    Else
        If Cell.Value = "X" Then
            wspGen.Range("AG55").Value = vbNullString
            wspGen.Range("A45").Value = "N"
            LP.zPledge.Value = "N"
            'Copies the corresponding value from range ("IneligibilityCode")
            'if there is an "X" in any of the cells in range ("Ineligible")
            'to I46.  This could be multiple combinations of values in range ("IneligibilityCode")
        End If
    End If
Next Cell


谢谢大家的帮助。

标签: excelvbaexcel-2013

解决方案


这是一个使用计数器变量的简单示例,假设两个范围都是单列且对齐的。它计算在找到 x 之前第一个命名范围(在变量 a 中设置)向下的单元格数量,并检索命名范围 b 中相同位置的值。注意我正在使用隐式活动工作表引用,您应该在命名范围之前指定工作表名称。

Option Explicit
Public Sub test()
    Dim a As Range, b As Range, rng As Range, counter As Long
    Set a = Range("range1"): Set b = Range("range2")
    For Each rng In a
        counter = counter + 1
        If rng = "x" Then
            Range("I46") = b.Cells(counter)
            Exit For
        End If
    Next
End Sub

所有匹配的空格分隔列表:

Option Explicit
Public Sub test()
    Dim a As Range, b As Range, rng As Range, counter As Long, outputString As String
    Set a = Range("range1"): Set b = Range("range2")
    For Each rng In a
        counter = counter + 1
        If rng = "x" Then
            outputString = outputString & Chr$(32) & b.Cells(counter)
        End If
    Next
    wspGen.Range("I46")  = Trim$(outputString) ' wspGen.Range("I46")  is defined in your code. This is illustrative.
End Sub

推荐阅读