在用vba处理单元格数据时,会遇到相同的单元格内容需要批量处理的情况。
如下图所示
A列的品类含有多个相同项,如果要把相同项所在的单元格区域罗列出来,可以使用如下的代码:
Sub QQ1722187970() Dim oWK As Worksheet Set oWK = Excel.Worksheets("Sheet1") Dim oRng As Range With oWK iRow = .Range("a65536").End(xlUp).Row End With '定义字典对象变量 Dim oDic As Object '创建字典对象 Set oDic = CreateObject("Scripting.Dictionary") For i = 2 To iRow With oDic sKey = oWK.Cells(i, 1).Value If .exists(sKey) Then '添加相同单元格内容的单元格区域 Set .Item(sKey) = Excel.Application.Union(.Item(sKey), oWK.Cells(i, 1)) Else .Add sKey, oWK.Cells(i, 1) End If End With Next i arrKeys = oDic.keys For i = 0 To UBound(arrKeys) Set oRng = oDic.Item(arrKeys(i)) Debug.Print oRng.Address Next i End Sub
发表评论