Counter to insert blank line every 5 equal cells

Asked

Viewed 573 times

2

Hello, I’m trying to make a macro for a button, which puts a blank line every 5 cells with equal content, but I’m quite layy in VB syntax and I’m not sure if the logic is correct either, example of what should happen:

ADA
ADA
ADA
ADA
ADA

ADA

My current code is this:

Private Sub Divide5_Click()
Dim Lst As Long
Dim n As Long
Dim i As Integer
Lst = Range("A" & Rows.Count).End(x1Up).Row
i = 0
For n = 2 To Lst Step 1
  With Range("A" & n)
    If .Value = .Offset(1).Value Then
     i = i + 1
    End If
    If i = 5 Then
     .EntireRow.Insert
    End If
  End With
Next n
End Sub

1 answer

3


You’re close, I made some modifications to get the interactions you want:

Sub Divide5_Click()
Dim Lst As Long
Dim n As Long
Dim i As Integer

Lst = Range("A" & Rows.Count).End(xlUp).Row
i = 0
n = 2
Do While n <= Lst 'For não itera dinamicamente
    With Range("A" & n)
        If .Value = .Offset(-1).Value Then
            i = i + 1
            If i = 4 Then
                .Offset(1).EntireRow.Insert
                i = 0 'Reinicie o contador após inserir linha
                Lst = Lst + 1 'limite dinâmico
            End If
        Else
            i = 0 'Reinicie o contador se a célula mudar de valor e não completar 5
        End If
    End With
    n = n + 1
Loop
End Sub
  • Thank you very much! You are also very close, haha, the first is with 6, the rest works perfectly.

  • hahaha my mistake, I thought the first cell was the name of the field and you don’t have to iterate it. I already correct the answer.

  • The idea is not bad, if I have a header I would certainly use it, but this plan only receives data to feed research of other plans.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.