Isabela
Isabela

Reputation: 13

AutoFill with Event Change VBA

I wrote this code below, but it's working just when I write something in Columns D and E and just doing the autofill for column C. The idea is that whenever I write something in any cell in a line higher than 4, the columns are autofilled. Does anyone know why it's not working and how could I solve it?

Private Sub Worksheet_Change(ByVal Target As Range)

Application.EnableEvents = False

Application.ScreenUpdating = False


If Target.Row >= 4 Then


Planilha3.Activate


ul = Cells(Rows.Count, "D").End(xlUp).Row


With Range("C4")

.FormulaR1C1 = "=RC[1]&RC[2]"

.AutoFill Destination:=Range("C4:C" & ul)

End With

With Range("B4")

    .FormulaR1C1 = "=IF(RC[1]<>"""",COUNTIF(R4C3:RC[1],RC[1]),"""")"
    
    .AutoFill Destination:=Range("B4:B" & ul)

End With

 
 With Range("A4")
 
 .FormulaR1C1 = "=RC[2]&RC[1]"
 .AutoFill Destination:=Range("A4:A" & ul)

End With

With Range("J4")

    .FormulaR1C1 = "=IFERROR(VLOOKUP(RC[-7],'Lista de Fornecedores'!C1:C4,2,FALSE),""Forn não cadastrado"")"
    .AutoFill Destination:=Range("J4:J" & ul)

End With

With Range("K4")

    .FormulaR1C1 = "=IF(RC[-1]=""Forn não cadastrado"",""Forn não cadastrado"", ""Recebido"")"
    .AutoFill Destination:=Range("K4:K" & ul)
  
End With


Application.EnableEvents = True


Application.ScreenUpdating = True



End If

End Sub

Upvotes: 1

Views: 252

Answers (1)

Super Symmetry
Super Symmetry

Reputation: 2875

Try this. I could not reproduce the issue you're experiencing, but this should do what you expect

Private Sub Worksheet_Change(ByVal Target As Range)
    On Error GoTo Cleanup

    Application.EnableEvents = False
    Application.ScreenUpdating = False

    Dim ul As Long
    
    If Target.Row >= 4 Then
        '* Assuming Planilha3 is the current sheet in question, you don't need to activate it
        'Planilha3.Activate
            
        ul = Me.Cells(Rows.Count, "D").End(xlUp).Row
        With Me.Range("A4:K" & ul)
            '* No need to autofill, you can set formulae to whole column at once
            .Columns("C").Formula = "=D4&E4"
            .Columns("B").Formula = "=IF(C4<>"""",COUNTIF($C$4:C4,C4),"""")"
            .Columns("A").Formula = "=C4&B4"
            .Columns("J").Formula = "=IFERROR(VLOOKUP(C4,'Lista de Fornecedores'!$A:$D,2,FALSE),""Forn não cadastrado"")"
            .Columns("K").Formula = "=IF(J4=""Forn não cadastrado"",""Forn não cadastrado"", ""Recebido"")"
        End With
    End If

Cleanup:
    Application.EnableEvents = True
    Application.ScreenUpdating = True
End Sub

Upvotes: 1

Related Questions