我使用以下VBA来连接具有公共ID的行
Function JoinAll(ByVal BaseValue, ByRef rng As Range, ByVal delim As String)
Dim a, i As Long
a = rng.Value
For i = 1 To UBound(a, 1)
If a(i, 1) = BaseValue Then JoinAll = JoinAll & _
IIf(JoinAll = "", "", delim) & a(i, 3)
Next
End Function
举个例子:
ID | Date | Purchase | Concat Value
1 | 3/4/16 | Car | Car, Cap
2 | 5/2/12 | Cat | Cat
1 | 6/2/13 | Cap | Cap
运行时,会创建Car,Cap。
但是,这是一个带过滤器的表,一旦过滤到它:
ID | Date | Purchase | Concat Value
1 | 3/4/16 | Car | Car, Cap
2 | 5/2/12 | Cat | Cat
它仍然显示Car,Cap而不是忽略Cap不可见。
我已经看到了这个答案,但是不知道如何让它与我目前的VBA一起使用:
Excel VBA Concatenate only visible cells of filtered column. Test code included
更新: 使用这个我只获得连接的可见项,但是我需要它来返回第3列中的值。这只返回第1列中的值:
Function JoinAll(ByVal BaseValue, ByRef rng As Range, ByVal delim As String)
For Each a In rng
If a = BaseValue And a.EntireRow.Hidden = False Then
JoinAll = JoinAll & IIf(JoinAll = "", "", delim) & a
End If
Next a
End Function
答案 0 :(得分:1)
你有没有试过像:
For each val in rng.Columns(3).Cells
If val = BaseValue And val.EntireRow.Hidden = False Then
JoinAll = JoinAll & IIf(JoinAll = "", "", delim) & val
End If
Next val
答案 1 :(得分:1)
这很有效。您的原始代码中有一个拼写错误/ a=rng.value
,因此在考虑隐藏的行时a
应为rng
。
Function JoinAll3(ByVal BaseValue, ByRef rng As Range, ByVal delim As String)
Dim a, i As Long
a = rng.Value
For i = 1 To UBound(a, 1)
If a(i, 1) = BaseValue And rng(i, 1).EntireRow.Hidden = False Then
JoinAll3 = JoinAll3 & IIf(JoinAll3 = "", "", delim) & a(i, 3)
End If
Next
End Function