去评论
距米网-精简版

依次查询H列内容和J列内容对比,如果含有8位数相同,那么单元格背景变成黄色

JUMU
2025/08/21 15:39:52
Excel VBA 编程:依次查询H列内容和J列内容对比,如果含有8位数相同,那么单元格背景变成黄色。

  1. Sub HighlightMatching8Digits()
  2.     Dim ws As Worksheet
  3.     Dim lastRow As Long
  4.     Dim i As Long
  5.     Dim hValue As String, jValue As String
  6.     Dim hDigits As Collection, jDigits As Collection
  7.     Dim digit As Variant
  8.    
  9.     ' 设置当前工作表
  10.     Set ws = ActiveSheet
  11.    
  12.     ' 获取最后一行数据
  13.     lastRow = ws.Cells(ws.Rows.Count, "H").End(xlUp).Row
  14.    
  15.     ' 循环处理每一行
  16.     For i = 1 To lastRow
  17.         ' 重置背景色
  18.         ws.Cells(i, "H").Interior.ColorIndex = xlNone
  19.         ws.Cells(i, "J").Interior.ColorIndex = xlNone
  20.         
  21.         ' 获取单元格值
  22.         hValue = CStr(ws.Cells(i, "H").Value)
  23.         jValue = CStr(ws.Cells(i, "J").Value)
  24.         
  25.         ' 提取H列中的所有8位数字
  26.         Set hDigits = Get8DigitNumbers(hValue)
  27.         
  28.         ' 提取J列中的所有8位数字
  29.         Set jDigits = Get8DigitNumbers(jValue)
  30.         
  31.         ' 检查是否有相同的8位数字
  32.         If HasCommonItem(hDigits, jDigits) Then
  33.             ' 如果有相同的8位数字,设置背景色为黄色
  34.             ws.Cells(i, "H").Interior.Color = vbYellow
  35.             ws.Cells(i, "J").Interior.Color = vbYellow
  36.         End If
  37.     Next i
  38.    
  39.     MsgBox "处理完成!", vbInformation
  40. End Sub

  41. ' 从字符串中提取所有8位数字
  42. Function Get8DigitNumbers(inputStr As String) As Collection
  43.     Dim regex As Object
  44.     Dim matches As Object
  45.     Dim match As Object
  46.     Dim result As New Collection
  47.    
  48.     Set regex = CreateObject("VBScript.RegExp")
  49.     With regex
  50.         .Pattern = "\b\d{8}\b"  ' 匹配8位数字
  51.         .Global = True         ' 全局匹配
  52.         .IgnoreCase = True     ' 不区分大小写
  53.     End With
  54.    
  55.     Set matches = regex.Execute(inputStr)
  56.    
  57.     For Each match In matches
  58.         result.Add match.Value
  59.     Next match
  60.    
  61.     Set Get8DigitNumbers = result
  62. End Function

  63. ' 检查两个集合是否有共同元素
  64. Function HasCommonItem(col1 As Collection, col2 As Collection) As Boolean
  65.     Dim item1 As Variant
  66.     Dim item2 As Variant
  67.    
  68.     For Each item1 In col1
  69.         For Each item2 In col2
  70.             If item1 = item2 Then
  71.                 HasCommonItem = True
  72.                 Exit Function
  73.             End If
  74.         Next item2
  75.     Next item1
  76.    
  77.     HasCommonItem = False
  78. End Function