Range Object Workout
- 04:39
Writing Excel VBA code to change the properties of a range object.
Transcript
In this workout, we need to write VBA code to write the word test into cell C7 and then apply a colour to the interior of that cell.
The first thing we need to do is go into the Visual Basic Editor by a developer and Visual basic.
We then insert a module.
We can keep the name of the module as module one, or we could change the name property to something else.
Let's keep the name as module one.
The first thing that we need to do in our procedure is to start it with the word sub.
Let's call our procedure something pretty intuitive.
We'll call it workout2.
As soon as we press enter LVBA automatically and adds the words end sub to the end of our procedure, and we are going to write our procedure code between subwork out two and end sub.
We require two lines of code here, the first to add the word test to sell C7, and then the second to change the colour property of the cells Interior.
It's really good practice to have each line of code on a separate line within VBA.
First of all, let's identify our range object.
Range C7.
C7 is held within quotes and we want to change the value property .val.
As soon as we start writing the word value.
We can see that auto list members is super, super useful here and we can see the value property.
Excel will automatically capitalize this if we have spelled the word value correctly and we will see value in auto list members.
If the value property is a property of the range object, we want to change that value and we want to apply a new value as it's text.
We hold this within quotes and we want the word test to go into range C7.
The range objects value property will be assigned the word test.
Next, we want to change the colour of the interior of cell C7.
The first thing that we do is we specify our range object range C7.
This time, As we type interior, we can see that the range object has an interior property.
Again, auto list members is super, super useful here.
That interior of the cell, we want to change its colour property, C-O-L-O-R.
We can see that the interior of the range object has a color property.
How do we know? Well, we can see it in auto list members and color has been capitalized.
We want to assign the colour property a different colour.
There's lots of ways we could do this.
I'll choose the visual basic VB green to make the interior of the cell a green colour.
Once I've pressed enter, my procedure is complete.
Let's go back into the front end of Excel and then run our code.
Back in the front end of Excel developer list macros, there's workout two.
We press run almost instantaneously.
The word test is added to C7 and a green shading is applied to the cell.
Excel executes each line of code sequentially, the first line of code.
Well, that adds the word test to C7.
The second line of code, the interior property of that range object and the interior's colour property is then changed to green.