Home » excel » excel – Copy Range value and format

excel – Copy Range value and format

Posted by: admin May 14, 2020 Leave a comment

Questions:

I am trying to copy Cells B2:B26 from sheet1 to sheet2 B8:B32 with the value and format if a change occurs in sheet 1. The problem is it seems to run in loop for about 10 seconds. I can’t see what’s wrong. This is my code:

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
   Copy_Range
End Sub

Sub Copy_Range()

Sheets("liste d'élèves").Range("B2:B26").Copy

With Sheets("Feuil1").Range("B8:B32").End(xlToLeft).Offset(, 1)
    .PasteSpecial xlPasteAll
End With

Application.CutCopyMode = False

End Sub
How to&Answers:

You need to disable events. Also, I highly recommend limiting the scope of your Worksheet_SelectionChange. Do you really want any change to trigger the macro? Maybe you are looking in a change within a specific region. If so, specify that region and run the macro when the selection change overlaps (Intersects) with the specified region.

Sub Copy_Range()

Application.EnableEvents = False <--- Off

Sheets("liste d'élèves").Range("B2:B26").Copy

With Sheets("Feuil1").Range("B8:B32").End(xlToLeft).Offset(, 1)
    .PasteSpecial xlPasteAll
End With

Application.EnableEvents = True <--- On

End Sub