VBA for beginners
Task 1: Hello World
- Create an Excel file with Macro-Enabled
- Setup the environment (Trust Center, Developer Tab)
- Insert a button
- Create a Macro Function SayHello (inside a module)
- Call function from a button (assign macro from a button)
Sub SayHello()
MsgBox (“Hello world”)
‘MsgBox(“Hello”) this is a comment
End Sub
Note: Hot key: Ctrl + Space for suggesting
Task 2: Increasing & Decreasing button
- Create 2 buttons (Higher and Lower)
- Define a new function
Sub higher_value()
Selection.Value = Selection.Value +1
End Sub
Sub lower_value()
Selection.Value = Selection.Value -1
End Sub
- Assign 2 functions to 2 buttons that were created in last step
- Test your results
Task 3: Change active cell
- Create 5 buttons (Up, Down, Left, Right, Home), click there to move the active cell.
Sub Home()
Worksheets (“Sheet2”).Range(“H8”).Select
End Sub
Sub Up()
Selection.offset(-1,0).Select
End Sub
Selection.offset(-1,0).Select = UP
Selection.offset(1,0).Select = DOWN
Selection.offset(0,1).Select = RIGHT
Selection.offset(0,-1).Select = LEFT
Task 4: Simple Loop and variables
Sub SimpleLoop()
Dim i As Interger
For i=1 To 10
Selection.offset(i-1,0)=i
Next
End Sub
Task 5: Create Sheet/Copy Sheet
Test these statements:
Sheets(“Du Lieu”).Copy Before:=Sheet(2)
Sheets(“Du Lieu”).Copy After:=Sheet(1)
MsgBox ActiveWorkbook.Sheets.Count
Sheet(3).delete
Application.DisplayAlerts = False //ignore delete warning
Sheet(“Du lieu”).delete
Task 6: Delete
Test these statements
Get specific value and rename worksheet
ActiveSheet.Name = Sheet(1). Range(“B8”)
Delete many worksheets using loop
Sub DeleteManyWorksheets()
Dim ws as Worksheet
Application.DisplayAlerts = False
For Each ws In ActiveWorkbook.Sheets
If ws.Index >2 Then
ws.delete
End if
Next ws
End Sub
Case study: Provide a list of staffs; for each staff, create a worksheet that contains
his/her personal information.