For循环捕获不同命名范围内的值

For loop to capture values in different named ranges

我一直在浏览多篇关于循环遍历多个命名范围并将值 returning 到另一个单元格的帖子。不幸的是,如果另一个命名范围中的单元格是 "X".

,我被困在如何遍历两个命名范围到 return 一个命名范围的值的问题上

下面是单元格 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


谢谢大家的帮助。

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

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

Space 所有匹配项的分隔列表:

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