gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 22:31:14 25 4
gpt4 key购买 nike

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

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

Named Ranges to loop through宏循环完成后的预期结果:
Result

代码:

    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 中相同位置的值。注意我正在使用隐式事件工作表引用,您应该在命名范围之前指定工作表名称。

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

关于excel - For循环捕获不同命名范围内的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52630192/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com