求助:如何用VBA合并重复行的单元格批注?
合并重复行的单元格批注解决方案
你的现有代码在合并重复行时仅处理了长度累加,未同步合并批注内容。要实现批注合并,需在删除重复行前,将待删除行的批注内容追加到保留行的批注中,具体修改如下:
修改后的去重代码
'Remove Duplicates Dim commentText As String For x = lastrow To 7 Step -1 For Y = 7 To lastrow If (.Cells(x, 1) = .Cells(Y, 1) And .Cells(x, 3) = .Cells(Y, 3) And _ .Cells(x, 4) = .Cells(Y, 4) And .Cells(x, 5) = .Cells(Y, 5)) And x > Y Then ' 累加电缆长度 .Cells(Y, 2) = .Cells(x, 2) + .Cells(Y, 2) ' 合并批注逻辑 If .Cells(x, 2).Comment Is Not Nothing Then commentText = .Cells(x, 2).Comment.Text If .Cells(Y, 2).Comment Is Nothing Then ' 保留行无批注时,直接添加新批注 .Cells(Y, 2).AddComment commentText Else ' 保留行已有批注时,用换行符分隔追加内容 .Cells(Y, 2).Comment.Text Text:=.Cells(Y, 2).Comment.Text & vbCrLf & commentText End If End If ' 删除重复行 Rows(x).EntireRow.Delete Exit For End If Next Y Next x
关键逻辑说明
- 先判断待删除行(x行)的B列是否存在批注,避免空指针报错
- 保留行(Y行)无批注时,直接复制待删除行的批注内容
- 保留行已有批注时,用换行符
vbCrLf分隔新旧批注内容,也可根据需求替换为其他分隔符(例如" | ") - 完成批注合并后再删除重复行,确保批注内容不丢失
内容的提问来源于stack exchange,提问作者Matt Taylor
相关产品推荐
相关产品推荐

