excel - 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
谢谢大家的帮助。
解决方案
这是一个使用计数器变量的简单示例,假设两个范围都是单列且对齐的。它计算在找到 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
推荐阅读
- node.js - Hapi 未知认证策略 jwt
- c# - C# 构造函数由于另一个构造函数而中断
- java - 读取包含无符号数的二进制流
- python - Airflow - 为 DockerOperator 获取并清理 run_id
- pycharm - 如何为 pycharm 和 spyder 设置站点包目录?
- python - 如何从下一个名称中减去存储在 python 列表中的列名?
- vba - 在 Access CSV 导出顶部附加其他行
- javascript - 多个地址自动完成字段?(#Google Places API & getElementById #)
- deep-learning - 如何在 Pytorch 中分别连接两个大小为 [B,C,13,18] 和 [B,C,14,18] 的张量?
- java - 如何模拟任务:Spring中的执行者