【发布时间】:2018-05-11 16:56:50
【问题描述】:
我搜索了论坛并找到了一些很棒的 Excel VBA 代码来查找和突出显示给定数据集范围内的重复单元格值。
但是,我的数据集中的单元格值是段落。这意味着数据集中的某些单元格值将大于 255 个字符。当我运行下面的代码时,重复的单元格会突出显示,直到代码遇到大于 255 个字符的单元格值。这似乎导致“countif”函数抛出错误:
运行时错误“1004”: 无法获取 WorksheetFunction 类的 CountIf 属性
关于如何将大于 255 个字符的 Cell.Value 传递给 CountIf 的任何想法,或比较大于 255 个字符的单元格值以突出显示重复项的其他想法?
Sub findDuplicates()
Const headRow As Integer = 7 'row that contains the table heading row for the dataset
Dim lastRow As Integer
Dim rng As Range
With ThisWorkbook.Worksheets(1)
lastRow = .Range("F" & Rows.Count).End(xlUp).Row 'finds last row in dataset
Set rng = .Range(Cells(headRow + 1, 6), Cells(lastRow, 6)) 'sets the range of the dataset between the headRow and lastRow
End With
For Each Cell In rng
If Application.WorksheetFunction.CountIf(rng, Cell.Value) > 1 Then 'tests if there is a duplicate
Cell.Interior.ColorIndex = 6 'highlight yellow
End If
Next Cell
End Sub
【问题讨论】:
-
您可以循环遍历范围并查看一个单元格是否等于另一个单元格。如果由于数据的大小而需要很长时间,您可以将数据存储在 VBA 数组中并在那里进行循环。