duplicates - 使用VBA比较和连接excel中的重复值
问题描述
我有一个 Excel 格式的报告,其中案例编号字段与其他字段存在一对多关系。例如:如果一个案例由多个团队处理,则每个团队都有单独的条目。
我试图通过比较案例编号来连接行值来删除重复项。
案例# 团队类型名称 国家
111 aa xx 国家名称
111 bb yy 姓名 国家
我希望输出为:
案例# 类型 团队 名称 国家
111 aa,bb xx,yy 国家名称
我有下面的VBA代码:
Sub mergeCaseNumberValues()
Dim lngRow As Long
With ActiveSheet
Dim columnToMatch As Integer: columnToMatch = 1
lngRow = .Cells(65536, columnToMatch).End(xlUp).Row
.Cells(columnToMatch).CurrentRegion.Sort key1:=.Cells(columnToMatch), Header:=xlYes
Do
If .Cells(lngRow, columnToMatch) = .Cells(lngRow - 1, columnToMatch) Then
For i = 2 To 12
.Cells(lngRow - 1, i).Value = .Cells(lngRow, i).Value & .Cells(lngRow - 1, i).Value
Next i
.Rows(lngRow).Delete
End If
lngRow = lngRow - 1
Loop Until lngRow = 1
End With
End Sub
它给了我:
案例# 类型 团队名称 国家
111 aabb xxyy NameName countrycountry
在数据中,每个条目只有团队和类型不同,其他值相同。如何修改我的 VBA 以获得结果?有人可以帮忙吗?
解决方案
我认为你需要改变这一点:
For i = 2 To 12
.Cells(lngRow - 1, i).Value = .Cells(lngRow, i).Value & .Cells(lngRow - 1, i).Value
对此:
For i = 2 To 12
.Cells(lngRow - 1, i).Value = .Cells(lngRow, i).Value & ", " & .Cells(lngRow - 1, i).Value
您需要修复连接器以插入逗号。
对于您的重复问题,我认为这样的事情可能会奏效。请记住,它是“空气代码”,完全未经测试,但应该让您朝着正确的方向前进:
For i = 2 To 12
If .Cells(lngRow, i).Value <> .Cells(lngRow - 1, i).Value Then
.Cells(lngRow - 1, i).Value = .Cells(lngRow, i).Value & ", " & .Cells(lngRow - 1, i).Value
Else
.Cells(lngRow - 1, i).Value = .Cells(lngRow, i).Value
End If
基本上,您想使用 IF 语句比较这些值,如果它们相等,那么您不想同时使用它们。
推荐阅读
- javascript - 如何比较不同对象javascript的选定键
- python - 可以在 PyCUDA 中将 int 变量从主机传输到设备吗?
- visual-c++ - 样本采集器接收器未设置媒体类型 GUID
- python - Python pytest-mock assert_has_calls
- javascript - 如何使用 Javascript 读取 HTML 元素的名称?
- java - 将 byte[] 转换为 MultipartFile
- python - 使用 pivot_table 拆分列
- excel - 从 Private Sub workbook_open() 上的输入声明公共变量
- javascript - 我可以在 nodejs 中模仿全局窗口对象吗?
- php - Laravel,Yajra Datatable,如果 y 那么如何返回 Yes else No