以下是在Excel中运行的VBA代码,实现对指定2列信息间每行字符的差异数量,最后的差异数量生成至最右侧的空白列的位置。该代码考虑了只遗漏第一个字符的情况。
```
Sub CompareColumns()
Dim lastRow As Long
Dim i As Long, j As Long, k As Long
Dim col1 As String, col2 As String
Dim diffCount As Integer
'设置需要比对的多组两列信息的列号和输出结果的位置
Dim columns(1 To 2, 1 To 3) As String
columns(1, 1) = "A"
columns(1, 2) = "B"
columns(1, 3) = "C"
columns(2, 1) = "D"
columns(2, 2) = "E"
columns(2, 3) = "F"
'循环遍历每一组两列信息,计算字符差异数量,并将结果输出到指定位置
For k = 1 To UBound(columns, 1)
col1 = columns(k, 1)
col2 = columns(k, 2)
lastRow = Cells(Rows.Count, col1).End(xlUp).Row
For i = 1 To lastRow
diffCount = 0
If Len(Cells(i, col1)) <> Len(Cells(i, col2)) Then
diffCount = Len(Cells(i, col1))
Else
For j = 1 To Len(Cells(i, col1))
If Mid(Cells(i, col1), j, 1) <> Mid(Cells(i, col2), j, 1) Then
If j = 1 And Abs(Asc(Mid(Cells(i, col1), j, 1)) - Asc(Mid(Cells(i, col2), j, 1))) = 1 Then
'如果只是遗漏了第一个字符,则不计入差异
Else
diffCount = diffCount + 1
End If
End If