|
本帖最后由 lukeforall 于 2020-9-9 09:43 编辑
我写了个类似的编码,应该可以完美解决大家的类似问题,大家只需修改 columnA 和 columnB 的列号, rowNum 首行,就可以了楼主的代码我也看了,简单的比较没有问题,但是会出现抽取的最大字串是合并后的字段的问题,也没有比较单字,相同文字但调换位置的修改不会高亮。
大家可以试下我的代码,有问题讨论
- Type MatchStruct
- substrText As String
- posAstart As Integer
- posBstart As Integer
- posAend As Integer
- posBend As Integer
- substrLength As Integer
- substrMatch As Boolean
- End Type
- Sub HighlightDiff()
- Dim columnA%, columnB%, rowNum%, rowMax%, i%, j%, posTmp%, temp%
- Dim strA$, strB$, substr$
- Dim substrList(5000) As MatchStruct
- Dim matchCount As Integer
- On Error Resume Next
- columnA = 1 'Index for current translation column
- columnB = 2 'Index for suggested translation column
- rowNum = 2 'Index for the first row to compare
- 'Format the range as red
- rowMax = Range("A65536").End(xlUp).Row
- Range(Cells(2, columnA), Cells(rowMax, columnA)).Font.Color = vbRed
- Range(Cells(2, columnB), Cells(rowMax, columnB)).Font.Color = vbRed
- For rowNum = 2 To rowMax
- 'skip blank rows
- If Len(Cells(rowNum, columnA).Text) = 0 Or Len(Cells(rowNum, columnB).Text) = 0 Then rowNum = rowNum + 1
- 'Extract longest to shortest common strings,and store their positions
- strA = LCase(Cells(rowNum, columnA).Value)
- strB = LCase(Cells(rowNum, columnB).Value)
- n = Len(strA)
- matchCount = 1
- For i = n To 1 Step -1
- For j = 1 To n - i + 1
- substr = Mid(strA, j, i)
- posTmp = InStr(strB, substr)
- If posTmp > 0 Then
- strA = Replace(strA, substr, String(i, "犇"), 1, 1, vbTextCompare)
- strB = Replace(strB, substr, String(i, "淼"), 1, 1, vbTextCompare)
- substrList(matchCount).substrMatch = True
- substrList(matchCount).substrText = substr
- substrList(matchCount).substrLength = i
- substrList(matchCount).posAstart = j
- substrList(matchCount).posBstart = posTmp
- substrList(matchCount).posAend = j + i - 1
- substrList(matchCount).posBend = posTmp + i - 1
- matchCount = matchCount + 1
- End If
- Next j
- Next i
- 'Check if the matches are in their original order, matches that are in different order will stay in red
- For i = 1 To matchCount - 1
- For j = 1 To i
- If substrList(i).posAend < substrList(j).posAstart And substrList(i).posBstart > substrList(j).posBend Or substrList(i).posAstart > substrList(j).posAend And substrList(i).posBend < substrList(j).posBstart Then
- substrList(i).substrMatch = False
- Exit For
- End If
- Next j
- Next i
- 'Set matched words back to black
- For i = 1 To matchCount - 1
- If substrList(i).substrMatch = True Then
- Cells(rowNum, columnA).Characters(substrList(i).posAstart, substrList(i).substrLength).Font.Color = vbBlack
- Cells(rowNum, columnB).Characters(substrList(i).posBstart, substrList(i).substrLength).Font.Color = vbBlack
- End If
- Next
- Next rowNum
- End Sub
复制代码
|
|