在Excel工作表中检测重复的function

我需要一个可以在指定的Excel列中检测重复的函数。 我有这个,但它不能正常工作。 它不能区分值“46.500”和值“46.5000”。 countif函数可能将单元格作为数字进行比较。 这些单元格格式为文本,我甚至试图在数字之前添加撇号。 没有运气。

Function check_duplicates(column As String) LastRow = Range(column & "65536").End(xlUp).row For x = LastRow To 1 Step -1 If Application.WorksheetFunction.CountIf(Range(column & "1:" & column & LastRow), Range(column & x).Text) > 1 Then check_duplicates = x ' return row with a duplicate x = 1 Else check_duplicates = 0 End If Next x End Function 

渔获是Countif的线。

有谁知道如何强制VBA CountIf函数比较单元格作为string或其他方式来检查重复在VBA?

在这种情况下,我通常会觉得很有用。

 Dim cn As Object Dim rs As Object strFile = Workbooks(1).FullName strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & strFile _ & ";Extended Properties=""Excel 8.0;HDR=No;IMEX=1"";" Set cn = CreateObject("ADODB.Connection") Set rs = CreateObject("ADODB.Recordset") cn.Open strCon strSQL = "SELECT F2, Count(F2) AS CountF2 FROM [Sheet1$] " _ & "GROUP BY F2 HAVING Count(F2)>1 " rs.Open strSQL, cn s = rs.GetString MsgBox s '' Or Sheets("Sheet2").Cells(2, 1).CopyFromRecordset rs 

假设所有“文本”单元格都是文本数字表示,那么以下更改将起作用:

 Function check_duplicates(column As String) Dim lastrow As Long Dim x As Long lastrow = Range(column & "65536").End(xlUp).Row For x = lastrow To 1 Step -1 If Application.WorksheetFunction.CountIf(Range(column & "1:" & column & lastrow), Val(Range(column & x).Text)) > 1 Then check_duplicates = x ' return row with a duplicate x = 1 Else check_duplicates = 0 End If Next x End Function 

它通过使用Val函数将条件单元格的值强制为一个值

CountIf函数不会将公式作为第二个参数,所以第二个参数应该是:

“=”&Range(column&x).Text

这里是基于Remou的代码的新版本。 这一个是多才多艺和MS Excel 2007的作品。

 Function check_duplicates(column As Integer) ' checks for duplicates in a column ' usage: column - numerical (A = 1, B=2 etc...) ' returns: "" - no duplicates, otherwise list of duplicates with numbers of occurrences Dim cn As Object Dim rs As Object strFile = ActiveWorkbook.FullName strSheet = ActiveWorkbook.ActiveSheet.Name ' connection string for Excel 2007 strcon = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & strFile & _ ";Extended Properties=""Excel 12.0 Xml;HDR=No;IMEX=1"";" Set cn = CreateObject("ADODB.Connection") Set rs = CreateObject("ADODB.Recordset") cn.Open strcon col = "F" & Trim(Str(column)) strsql = "SELECT " & col & ", Count(" & col & ") AS Count" & col & " FROM [" & strSheet & "$]" & _ "GROUP BY " & col & " HAVING Count(" & col & ")>1 " rs.Open strsql, cn If rs.BOF = True And rs.EOF = True Then check_duplicates = "" Else check_duplicates = rs.GetString End If End Function