excel 用VBA如何删除一列中的重复数据

2025-01-20 13:18:29
推荐回答(4个)
回答1:

1、打开要进行数据处理的表格,

2、按ALT+f11,进入VBE程序操作页面,

3、将鼠标下移,右键弹出如图,

4、选择插入-模块,

5、鼠标向右移动,将如下代码写入:

Sub test()

Dim d As Object

Dim r%, i%

Dim arr

Set d = CreateObject("scripting.dictionary")

With Worksheets("sheet1")

r = .Cells(.Rows.Count, 3).End(xlUp).Row

arr = .Range("c2:d" & r)

For i = 1 To UBound(arr)

d.RemoveAll

For j = 1 To Len(arr(i, 1))

ch = Mid(arr(i, 1), j, 1)

d(ch) = ""

Next

arr(i, 2) = Join(d.Keys, "")

Next

.Range("d2").Resize(UBound(arr), 1) = Application.Index(arr, 0, 2)

End With

End Sub

6、按F5,运行代码,后返回工作表,会发现单元格中的重复字符已经被去掉。

回答2:

对于删除重复数据,Excel 2007中有一个功能可以删除,不需要VBA编程。

方法:

选中重复数据出现的单元格区域→“菜单”栏→“数据”→“删除重复项”→点击“确定”即可

如图:

回答3:

Option Explicit

Sub sample()
Dim j As Integer
Dim src As String, dst As String
Dim d
Set d = CreateObject("Scripting.Dictionary")

src = "BG"
dst = "BH"

With ActiveSheet
For j = 1 To .Range(src & .Rows.Count).End(xlUp).Row
If Not d.exists(Trim(.Range(src & j))) Then d.Add Trim(.Range(src & j)), ""
Next

.Range(dst & 1).Resize(d.Count) = WorksheetFunction.Transpose(d.keys)
End With

Set d = Nothing
End Sub

回答4:

excel 自带功能就有删除重复项啊……