Visual Basic For Applications
Visual Basic For Applications
Mike Pangburn
1
3/7/13
2
3/7/13
Notice that the code starts with Sub command and ends with End Sub command.
Sub refers to the Subroutines.
◦ Subroutine: A portion of code within a larger program that performs a specific task and is
relatively independent of the remaining code.
◦ We can use a subroutine in a different subroutine by “calling” it.
◦ e.g., Call Shifter().
CODE BLOCK
End Sub
Sub ShiftOneColumn (RowNum As Integer) We now have a subroutine that can correct any given row.
We want to apply this subroutine to any rows between 6 and 18.
Range("D" & RowNum & ":F" & RowNum).Select
Selection.Cut We use a loop (e.g., a FOR-NEXT Loop) for this task:
Range("C" & RowNum).Select For-Next Loop Syntax
ActiveSheet.Paste
For varName=start_val To end_val Step step_size
◦ In Excel and VBA the & operator simply combines (“concatenates”) text together
3
3/7/13
So, we add a line before the loop where we declare our variable
RowNum.
We need to check whether the first column of a row is empty or not.
VBA’s conditional statement IF-THEN-ELSE allows us to achieve this
goal.
IF-THEN-ELSE Syntax
If test_cond Then
...
CODE BLOCK executed if test_cond holds
Sub ShifterLoop
...
Dim RowNum As Integer Else
...
For RowNum=6 To 18 Step 1 CODE BLOCK executed if test_cond fails
Call ShiftOneColumn(RowNum) ...
End If
Next RowNum
End Sub
We could write our conditional statement to check the first column Functions are not always the right choice:
◦ A function cannot directly write data back to the spreadsheet.
within the subroutine, but we will define a separate “Function” for ◦ We can write data to the spreadsheet via subroutines. Easiest way:
the checking task. How to write data to cells
Cells(row_num,col_num).Value= x
Functions are very similar to the subroutines. Then, why a function? ◦ e.g., Cells(10,3).Value= "Ducks Rock" writes Ducks Rock to the cell
◦ Unlike a subroutine, but Functions return a value. C10. (Try it!)
◦ Useful for reporting the result of a calculation or other results. ◦ In this example, our function doesn’t need to change the value of cell,
◦ Our function will return… but our function does return a value.
1 if the first column is empty
0 otherwise.
4
3/7/13
Let’s go back to our task: Creating a function to check the first column. Sub ShifterLoop ()
We name our function as CheckColOne. Dim RowNum As Integer