这篇是 2020 年 6 月记的,大学里第一次为了一张表去写宏。代码原样贴着:
MsgBox当调试输出、Dim写在循环里、变量名叫dontknow,都没动。
要做的事:选中两列,从第一行往下逐字对齐比较,哪里不一样,就把后面的内容弹出来。
Function diffcell(cell1 As Range, cell2 As Range)
Dim str1 As String, str2 As String
str1 = cell1.Text
str2 = cell2.Text
Dim i As Integer, j As Integer
i = 1
j = 1
While i <> Len(str1) And j <> Len(str2)
If Mid(str1, i, 1) = Mid(str2, j, 1) Then
i = i + 1
j = j + 1
Else
Dim afterward1 As String, afterward2 As String
afterward1 = Mid(str1, i)
afterward2 = Mid(str2, j)
Dim foundIdx1 As Integer, foundIdx2 As Integer
foundIdx1 = InStr(i, str1, afterward2)
foundIdx2 = InStr(j, str2, afterward2)
MsgBox Mid(str1, foundIdx1 - i)
If foundIdx1 < foundIdx2 Then
MsgBox Mid(str1, foundIdx1 - i)
i = foundIdx1
Else
MsgBox Mid(str2, foundIdx2 - j)
j = foundIdx2
End If
End If
Wend
If i < Len(str1) Then
MsgBox Mid(str1, i)
Else
MsgBox Mid(str2, j)
End If
End Function
Sub test()
Dim rng As Range
On Error Resume Next
Set rng = Selection
On Error GoTo 0
If rng Is Nothing Then
MsgBox "未选择区域"
Return
End If
If TypeName(rng) <> "Range" Then
MsgBox "选的不是格子"
Return
End If
If rng.Columns.Count <> 2 Then
MsgBox "选中列数量应为2"
Return
End If
Dim skipRow As Integer
skipRow = 1
For i = 1 + skipRow To rng.Rows.Count
Dim cell1 As Range, cell2 As Range
Set cell1 = rng.Cells(i, 1)
Set cell2 = rng.Cells(i, 2)
Dim dontknow As Variant
dontknow = diffcell(cell1, cell2)
Next i
End Sub
现在回头看
While i <> Len(str1):用不等号收尾,最后一个字符永远比不到,得写<=。Mid(str1, foundIdx1 - i):Mid的第二个参数是起始位置,我当时按长度用了。想取中间一段得写Mid(str1, i, foundIdx1 - i)。If之前那句MsgBox跟两个分支里的重复,是调日志时留下的。Sub里用Return提前退出:VBA 的Return是配GoSub用的,这里应该写Exit Sub。diffcell没有返回值,所以dontknow拿到的一直是空。