excel宏里如何利用if语句插入行

2026年09月09日 01:04
有2个网友回答
网友(1):

Sub Macro2()
    Dim i, j As Integer
    For i = 50 To 3 Step -1
        If Cells(5, i) <> Cells(5, i - 1) Then
            Rows(i).Insert Shift:=xlDown
        End If
    Next i
End Sub


  1. 因为插入后行会往下推,所以为了避免行号的影响需要由下而上循环

  2. i变量在For循环中会自己按照Step递增,所以不需要在循环体内赋值

以上代码请测试

网友(2):

经测试,下面的代码可用
Dim i As Long

i = 3
Do
If Cells(i, 5).Value <> Cells(i - 1, 5).Value And Cells(i, 5).Value <> 0 Then
Rows(i).Insert shift:=xlDown
i = i + 1
End If
If Cells(i, 5) = 0 And i > Sheet1.UsedRange.Rows.Count Then Exit Do
i = i + 1
Loop