在遍历多个命名范围并将值返回到另一个单元格时,我一直在浏览多个帖子。不幸的是,如果另一个命名范围中的单元格为“ X”,我将陷入如何遍历两个命名范围以从一个命名范围返回值的问题。
下面是带有值的指定范围的图像以及单元格I46中的预期结果。请注意,I46中没有公式。
命名范围:
Range1 Range2
代码:
Input:
FTX+AAA+++201707141009UTC'
FTX+BBB+++201707141009UTC'
FTX+CCC+++201707141009UTC?:??'
PISCO US LTS;?:V.D??'
SOUZA?:GB?:GB'
FTX+ZZZ+++201707141009UTC'
Expected Output:
Number of segments: 4
Input:
FTX+AAA+++201707141009UTC'
FTX+CCC+++201707141009UTC?:??'
PISCO US LTS;?:V.D??'
FTX+ZZZ+++201707141009UTC'
Expected Output:
Number of segments: 3
谢谢大家的帮助。
答案 0 :(得分:2)
这是一个使用计数器变量的简单示例,假定两个范围均为单列且对齐。它计算在第一个命名范围内有多少个单元格 (在变量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