VBA Basic Syntax Explanation and debugging Part 1

This is just to introduce you on the basic syntax of excel VBA.

First pattern:
Example
  In sentence:
      The color of the cell is green.
  Cell - object
  Color - properties
  green - adjective

In VBA the pattern is like this:

OBJECT.PROPERTIES=ADJECTIVE

Definition of Terms
1. Object
   This is the subject of your syntax.
   Examples are workbook, worksheet, cell , range,name etc
2. Properties
   It's like a parameters. What part of the worksheet you want to color?
   Examples are color, size, width, font size,value etc.
3. Adjective
  Describe the properties of your object.
  Examples are green,bold, MySheetName, etc.

So let's try your first code.

In your VBA Project of your VBA Editor, select the module. If you have no idea, please see this tutorial.

If you have an existing program, you can add anywhere you want.

Your code should be looked like this. Don't forget to end your sub by putting end sub.

     SUB MyFirstCode


     End Sub

Inside your content, try this one.

     SUB MyFirstCode
           
             Range("A1").Value = 1

     End Sub



Click Run.
Run   Pause Stop
I hope it works.

You can add comment.
     SUB MyFirstCode
           ' this is my first code
             Range("A1").Value = 1 'Cell A1 value is 1

     End Sub

Take Note:
Range () is already a built in code in VBA. So all you need to do, is to give the value.
"" indicates that this is the value.

Or, you can add more.
     SUB MyFirstCode
           ' this is my first code
             Range("A1").Value = 1 'Cell A1 value is 1
             Range("A1").Interior.Color = 255  'Cell A1 value color is red
                                                                 ' there is equivalent number for each color 255 is for red
     End Sub

Tips:
1. You don't need to memorize all these properties since VBA will give suggestions.
2. Record macro first on what you want then you can edit the recorded code.

Tricks
You can you use F8 to run your each line of your code.
Through this one, you can see how is the flow of your program.`

I will give you more example using other pattern. We will tackle Method.


No comments:

Post a Comment