Range Objects and Methods Workout
- 04:27
Workout demonstrating the use of the current region property and application of the copy method.
Transcript
In this workout, we are required to write VBA code to copy the current region of cell C7 and copy this range 5 columns to the right.
In order to write our code, we need to go into the visual basic Editor, developer Visual Basic.
We're going to write our code into a module insert module.
Our module is called module one by default, and to start, we write the word sub.
Let's call our sub procedure by an intuitive name.
We'll call it Workout3.
As soon as we press enter on workout3, the words end sub are added.
We will write the code for our procedure between the sub workout three line and the end subline.
In this example, we are going to combine objects, properties, and methods, and we required to write VBA code to copy the current region of cell C7 five columns to the right.
If we're not sure what the current region of cell C7 is writing the code range C7 dot current region.select will show us where that current region sits.
We don't need to do that here, but we do need to say what the current region of cell C7 is in order for it to be copied.
Let's start off by firstly specifying the range object, and we do that with range quotes C7 Current region.
Having the auto-populate members is a really, really useful addition here.
Having that option checked means that we can see the current region property with that current region.
We want to apply its copy method again, dot, and then copy.
We can see the copy method is available.
The copy method can be applied to that current region.
Property pressing space.
Auto list info again is really, really useful.
It will tell us all of the required arguments for the copy method.
There's only one argument and that is the destination.
The destination will be a range object that will be range C7, but we want to put it five columns to the right.
So we are going to use the offset property.
Again, auto list members is really, really useful because the range object has an offset property.
Auto quick info tells us that there are two required parameters, the number of rows to offset, and the number of columns.
Well, we want zero rows and five columns.
What will be returned is a range.
Once we press enter, our procedure is complete.
We can go back to the front end of Excel and we can run our code back to Excel.
Let's try and run our code developer macros.
There's work out three, we'll press run and let's take a look at what happened.
First of all, the current region of range C7 was specified.
We then applied the copy method and we copied this 1, 2, 3, 4, 5 columns to the right.
And as you can see, that is what our code has done.