我在同一个Excel工作表中有两个columns A and B
。我正在尝试,如果在Column B
两个值匹配,那么它应该在同一行中复制相关值A
。
例如
表
Column A Column B
xyz 1
abc 1
pqr 1
eee 2
qqq 3
www 4
oop 5
Desierd输出
column A Column B
xyz,abc,pqr 1
eee 2
qqq 3
www 4
oop 5
答案 0 :(得分:5)
您可以使用用户定义函数(也称为UDF)。把它放到模块表中。
Public Function conditional_concat_strs(rSTRs As Range, rCRITs As Range, rCRIT As Range, Optional sDELIM As String = ", ")
Dim c As Long, sTMP As String
Set rSTRs = rSTRs.Cells(1, 1).Resize(rCRITs.Rows.Count, rCRITs.Columns.Count)
For c = 1 To rCRITs.Cells.Count
If rCRITs(c).Value2 = rCRIT Then _
sTMP = sTMP & rSTRs(c).Value & sDELIM
Next c
conditional_concat_strs = Left(sTMP, Application.Max(Len(sTMP) - Len(sDELIM), 0))
End Function
像任何本机工作表函数一样使用。
答案 1 :(得分:2)
你也可以使用这个:
Public Sub combine()
Dim row, result, lastRow As Integer
Dim isExist As Boolean
With Sheets("sheetname")
'get the last use row
lastRow = .Range("A1").SpecialCells(xlCellTypeLastCell).row
'Loop from row 1 to last row
For row = 1 To lastRow Step 1
'set the start row for result.
result = 1
'Reset flag
isExist = False
'Loop result count column until blank
Do While .Range("F" & result) <> ""
'check count
If .Range("B" & row) = .Range("F" & result) Then
isExist = True
'If old, combine
.Range("E" & result) = .Range("E" & result) & "," & .Range("A" & row)
Exit Do
End If
'increase row
result = result + 1
Loop
'If new, add new record
If Not isExist Then
.Range("E" & result) = .Range("A" & row)
.Range("F" & result) = .Range("B" & row)
End If
Next row
End With
End Sub
在这里,测试我的代码的证据:
我使用column A & B
作为输入,column E & F
作为输出。
如果有任何问题,请告诉我。
答案 2 :(得分:0)
还有一个公式解决方案(带辅助列):
假设数据是A列:B ......
=IF(A1<>A2,B2,D1&","&B2)
=IF(A2<>A3,A2,"")