【问题标题】:For loop to capture values in different named rangesFor循环捕获不同命名范围内的值
【发布时间】:2018-10-03 15:08:31
【问题描述】:

我一直在查看有关循环多个命名范围并将值返回到另一个单元格的多个帖子。不幸的是,如果另一个命名范围中的单元格是“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


谢谢大家的帮助。

【问题讨论】:

  • 您是否需要另一个命名范围中的行值与您在第一个中找到 X 的位置相同?如果是这样,您可以使用找到的 .Row 。如果是相对定位,则可能是索引。
  • 正确。如果“X”是第一个命名范围中的一个单元格,那么我需要来自另一个命名范围的相应值(来自图像 1)。我还是个 VBA 新手,请问您能提供一个代码示例吗?

标签: excel vba excel-2013


【解决方案1】:

这是一个使用计数器变量的简单示例,假设两个范围都是单列且对齐的。它计算第一个命名范围内有多少个单元格 (在变量 a 中设置)它在找到 x 之前并检索命名范围 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

【讨论】:

  • 谢谢。我使用该示例更改了我的代码,但现在我坚持如何从InelCode.Cells(counter) 获取值以显示在单元格 I46 中。就像图 2 中的示例一样。
  • 如果它们在同一张纸 Range("I46") = b.Cells(counter) 中。否则将工作表名称放在前面。 Worksheets("mySheet").Range("I46") = b.Cells(counter) 您应该始终使用父工作表引用。
  • 我设置了wspGen.Range("I46") = InelCode.Cells(counter),但它只显示范围 2 中的最后一个值,该值在范围 1 中有一个“X”。在这种情况下,它将是“P”。
  • 由于范围 2 中可能有多个值显示在“I46”中,我需要范围 2 中在范围 1 中具有“X”的所有值。
  • 这很简单。你想要一个空格分隔的列表吗?见编辑。
猜你喜欢
  • 1970-01-01
  • 2017-07-05
  • 1970-01-01
  • 1970-01-01
  • 2013-07-15
  • 1970-01-01
  • 1970-01-01
  • 2016-12-21
  • 2012-06-12
相关资源
最近更新 更多