VBA For Excel
VBA For Excel
Sub proTest()
End Sub
Lesson 5: Developing Macros
in Excel
Sub proTest()
Sheets("Sheet1" ).Select
Range("C1" ).Select
Do Until Selection.Offset(0, -2).Value = ""
Selection.Value = Selection.Offset(0, -2).Value & " " &
Selection.Offset(0, -1)
Selection.Offset(1, 0).Select
Loop
Range("A1" ).Select
End Sub
Lesson 6: Testing Macros in the
Visual Basic Editor for Excel
Lesson 7: The Excel Macro
Recorder
• Sheets("Sheet1").Name= "Results"
Lesson 15: Working with
Worksheets
• You access a worksheet named " Balance" with:
Sheets("Balance").Select
Note that the word "Sheets" is plural and always use the quotes within the parenthesis
• You cannot select a sheet that is hidden so you will need to write:
Sheets("Balance").Visible= True
Sheets("Balance").Select
and then if you want to hide the sheet again:
Sheets("Balance").Visible= False
• The name of a sheet must not have more than 31 characters and should not include certain
special characters like " ? : \ / [ ]" . If you do not respect these rules your procedure will crash.
• The following lines of code will generate an error message:
Sheets("Sheet1").Name= "Balance and Introduction to Numbers" because there are more
than 31 characters including the spaces
Sheets("Sheet1").Name= " Balance: Introduction" because of the special character :
Sheets("Sheet1" ).Name= " " because the name cannot be blank
• You can not go directly from a sheet to a cell on another sheet. For example if the active sheet is
"Balance" and you want tot go to cell A1 of a sheet named " Results" you cannot write:
Sheets("Results").Range("A1").Select
You must take two steps:
Sheets("Results").Select
Range("A1").Select
Lesson 16: Moving Around the
Worksheet
• Cells
• Ranges
• Columns
• Rows
Lesson 16: Cells
• A lot of VBA beginners start their career using Cells. For example:
Cells(1,1).Select is the same thing as Range("A1").Select and
Cells(11,31).Select is the same as Range("AE11").Select.
• The only time that you will use Cells is when you want to select all
the cells of a worksheet. For example:
Cells.Select
To select all cells and then to empty all cells of values or formulas
you will use:
Cells.ClearContents
Lesson 16: Range
Sub proLessson17a()
Sheets("Sheet1").Select
Range("A1").Value = 695
MsgBox "The macro has finished running"
End Sub
Lesson 17: b
Sub proLessson17b()
Sheets("Sheet1").Select
Range("A1").Value = 695
MsgBox "The result is in cell ""A1"""
End Sub
Lesson 17: c
Sub proLessson17c()
Sheets("Sheet1").Select
Range("A1").Value = 695
MsgBox "The result is " & Range("A1").Value
End Sub
Lesson 19: Working with Variables
• Hard Coding vs Dynamic Coding
Sub proDelete()
Do Until Selection.Value = "xxx"
If Selection.Value = "" Then
Selection.EntireRow.Delete
Else
Selection.Offset(1, 0).Select
End If
Loop
Range("A1").Select
End Sub