VBA in Excel

AutoFill and Formulae

Values & Formulae

This part is very easy! To set a cells value, simply use the Value property:

ActiveCell.Value = "hello!"

To specify a formulae, you use the Formula property:

Range("A2").Formula = "=2+2"

Simple!

AutoFill

Another very useful function in Excel is the ability to write one formula, and drag it across multiple cells, with Excel automatically changing cell references as required. You can use this in your Macros too, by using the AutoFill function. AutoFill takes the following parameters:

AutoFill DestinationRange, Type

Note that instead of passing "A2" in DestinationRange, you pass the Range object. This lets you use either Range or Cells to get the cells you want. So, to AutoFill from A1 to A2 through to A6 (A2:A6), you simply pass:

Range("A1").AutoFill Range("A1:A6"), xlFillDefault

Note that you must include the source range in the destination! In some cases, such as incrementing numbers, you will need to give Excel two cells so that it can work out the interval:

Range("A1:A2").AutoFill Range("A1:A6"), xlFillDefault

If the AutoFill doesn't do what you want by default, you can specify a different AutoFill method in the place of xlFillDefault:

AutoFill Types
xlFillCopy
xlFillDays
xlFillDefault
xlFillFormats
xlFillMonths
xlFillSeries
xlFillValues
xlFillWeekdays
xlFillYears
xlGrowthTrend
xlLinearTrend

For more info, take a look at the Excel VBA help.

You might also like...

Comments

About the author

James Crowley

James Crowley United Kingdom

James first started this website when learning Visual Basic back in 1999 whilst studying his GCSEs. The site grew steadily over the years while being run as a hobby - to a regular monthly audien...

Interested in writing for us? Find out more.

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“Better train people and risk they leave – than do nothing and risk they stay.” - Anonymous