Page 46 - Excel for Scientists and Engineers: Numerical Methods
P. 46

CHAPTER 2     FUNDAMENTALS OF PROGRAMMING WITH VBA                    23



                Other Keywords
                   In  addition to VBA's  objects, properties, methods and  functions,  there are
                additional keywords that deal with program control: looping, branching  and so
                on.  These keywords are described in detail in the following sections.
                   VBA keywords that will not be discussed in this book include objects such
                as  menu  bars,  menus  and  menu  commands,  toolbars  and  toolbuttons  and  the
                many properties and methods pertaining to them.


                Program Control

                   If you are familiar with computer languages such as BASIC or FORTRAN,
                you will find yourself quite comfortable with most of the material in this section.


                Branching
                   VBA  supports  If ... Then  statements  very  similar  to  the  Excel  worksheet
                function IF.  The syntax of If ... Then is

                   If LogicaExpression Then statement? Else statement2
                   The If ... Then statement can be a Simple If statement, for example:
                       If (x PO) Then numerator = 10 ,-, x

                   If  LogicaExpression (in  this example x  > 0) is True, statement? is carried
                out; if LogicaExpression is False, nothing is done (program execution moves to
                the next line).
                   If ... Then. ..Else structures are also possible.  For example:

                   If Err.Number = 13 Then Resume ptl Else End
                   In a Block If statement,  If LogicaExpression Then is followed by multiple
                statement lines and is terminated by End If, as in Figure 2-1.
                    If Err.Number = 13 Then
                       On Error GoTo 0    'Disable the error handler.
                       Resume ptl    'and continue execution.
                    End If
                              Figure 2-1.  Example of VBA Block If structure.

                    You  can  also  create  a  Block-If-type  structure  in  a  single  line,  as  in  the
                following statement.

                    If LogicaExpfession Then statement? : statement2 Else statement3
                    If ... Then ... Elself structures are also possible, as illustrated in Figure 2-2.
   41   42   43   44   45   46   47   48   49   50   51