Monday, June 20, 2005

 

Rule 10: Copy and Paste in VBA is evil

Just like select and selection, copy and paste in VBA codes is also evil. Its a side effect problem again and it can be avoided.

Here is some typical generated code.


Range("A13:B23").Select
Selection.Copy
Range("A26:B36").Select
ActiveSheet.Paste


Taking out the select, we still have a problem.


Range("A13:B23").Copy
Range("A26:B36").Paste


It still has a side effect of putting some values in the clipboard.

Here is some code that does the job without any side effects.


Range("A26:B36").value = Range("A13:B23").value


Shorter and side effect free.

It also means the user isn't surprised if they run a macro and then try and paste what they thought was in the clipboard into a new range or cell.
Comments: Post a Comment





<< Home

This page is powered by Blogger. Isn't yours?

Subscribe to Posts [Atom]