以下是一个示例代码,可以比较两列数据,并在其中的一列中找到任何不同的行,然后插入一个新行,可以插入在不同行的上方或下方,具体取决于用户的选择。
Sub CompareAndInsert() Dim firstColumn As Range, secondColumn As Range, i As Long, j As Long Dim insertDirection As String, insertRow As Long
Set firstColumn = Range("A1:A" & Cells(Rows.Count, 1).End(xlUp).Row)
Set secondColumn = Range("B1:B" & Cells(Rows.Count, 2).End(xlUp).Row)
insertDirection = InputBox("Enter 'above' or 'below' to specify where to insert new rows: ")
For i = 1 To firstColumn.Count
If firstColumn.Cells(i).Value <> secondColumn.Cells(i).Value Then
insertRow = i
If insertDirection = "above" Then
Rows(insertRow).EntireRow.Insert shift:=xlDown
ElseIf insertDirection = "below" Then
Rows(insertRow + 1).EntireRow.Insert shift:=xlDown
End If
Exit For
End If
Next i
End Sub