Excel VBA脚本比较两组数据和ID排列

我正在拼凑一个VBA脚本,比较两列数据(每行大约15,000行),并确定是否有任何单元格是另一个单元格的排列。

例如,如果A1 = 15091和B52 = 19510,那么函数会将它们标识为具有相同的一组字符。

我有一个循环设置,检查列A中的每个单独的单元格与列B中的每个其他单元格和循环内的各种函数,但迄今为止任何将完成此任务的任何成功都不成功。

此外,由于“数字”格式的单元格将在小数点之后全部舍去零,因此15091.1将不会被识别为与15091.01相同的字符集。

您可以使用纯Excel方法在没有VBA的情况下执行此操作。 (尽pipe下面find了VBA解决scheme)这个想法是为每个数字集合的每个排列组成一个相同的“哈希值”,而不与其他哈希值重叠。

人们会这样做是:

  1. 计算每个数字的数字0-9(例如,15091和19510将是1×0,2×1,1×5和1×9)
  2. 用10 ^数字(例如1 * 10 ^ 0 = 1,2 * 10 ^ 1 = 20,1 * 10 ^ 5 = 100000,1×10 ^ 9 = 1000000000)乘以每个计数。
  3. 总和这些产品(例如1000100021)

然后,你所要做的就是将这些散列相互匹配(使用Excel的MATCH函数),看看是否有东西被find(使用ISERROR函数)。

Excel的分步说明(假设您的数据在Sheet1和Sheet2的列A中,从A1开始:

  1. 在Sheet1中:
  2. 在上面插入两行
  3. 在B3中,将这个公式=TEXT(A3,"0") – 这将摆脱每个数字的余数,并将其转换为文本。 复制公式直到您的范围结束
  4. 在C1:L1中,放置数字0,1,2 …
  5. 在C2:L2中,公式=10^C1
  6. 在C3中,放置这个公式: =LEN($B3)-LEN(SUBSTITUTE($B3,C$1,"")) – 并将它复制到右边直到列L并向下到列表的末尾。 这将计数位数
  7. 在M3中,放置这个公式: =SUMPRODUCT(C3:L3,$C$2:$L$2) – 这将计算散列
  8. 重复Sheet2中的步骤2-7
  9. 在Sheet1中,将此公式放在N3中: =NOT(ISERROR(MATCH(M3,Sheet2!$M:$M,0)))

完成!

这是一个VBA解决scheme:

 Option Explicit Sub IdentifyMatches() Dim rngKeys As Range, rngToMatch As Range, rngCell As Range Dim dicHashes As Object 'the range you want to have highlighted in case of a match Set rngKeys = Sheets("Sheet1").Range("A3:A5") 'the range to search for matches Set rngToMatch = Sheets("Sheet2").Range("A3:A5") Set dicHashes = CreateObject("Scripting.Dictionary") 'Create dictionary of hashes (dictionary is used for its .Exists property For Each rngCell In rngToMatch dicHashes(GetHash(rngCell)) = True Next 'Check each cell in rngKey if it has a match For Each rngCell In rngKeys If dicHashes.Exists(GetHash(rngCell)) Then 'Action to take in case of a match rngCell.Font.Bold = True Debug.Print rngCell.Value & " has a match!" Else rngCell.Font.Bold = False End If Next End Sub Function GetHash(rngValue As Range) As Long Dim strValue As String Dim i As Integer, digit As Integer Dim result As Long Dim digits(0 To 9) As Integer 'Potentially add error check here strValue = Format(rngValue.Value, "0") For i = 1 To Len(strValue) digit = Int(Mid(strValue, i, 1)) digits(digit) = digits(digit) + 1 Next i For i = 0 To 9 result = result + 10 ^ i * digits(i) Next i GetHash = result End Function 

最后但并非最不重要的, 这里是示例文件 。