r/excel • • Feb 04 '14

discussion VBA Macro code best practices?

Every programming language has its recommended style and best practices. What are the best practices for VBA code that you follow? What resources would a new coder use to learn these best practices?

Thank you in advance!

18 Upvotes

36 comments sorted by

View all comments

Show parent comment

9

u/[deleted] Feb 04 '14 edited Feb 04 '14

To expand on this, .Copy should be avoided:

Range("A1").Copy
Range("B1").Paste

Becomes

Range("A1").Copy Range("B1")

And even better:

Range("B1") = Range("A1")

Or if you want values only:

Range("B1").Value = Range("A1").Value

You can also use .Cells instead of "B1" etc. This is great for looping or dealing with columns in terms of integers instead of letters etcl.

Range("A1:A100")
Range(Cells(1, 1), Cells(100, 1))

Then you have sheet references (using the activesheet is a bad idea usually).

Set oSht = Worksheets("sheetname")
Set oSht = Worksheets.Sheet1
Set oSht = Worksheets.Sheets(1)

Using this, you'd be able to target hidden sheets etc.

oSht.Cells(1,1).Value = oSht.Cells(1, 2).Value

3

u/ht1237 4 Feb 04 '14

Seconded on the setting the ranges equal to one another. This saves a lot of time and keeps your clipboard clean. I don't want to know how many imgur links I have accidentally copied into a spreadsheet during my career!