Université EUROMED de Fès
Euromed Business School
VBA for Excel
Introductory Lab
Exercise 1:
Record a Simple Macro: Formatting Cells
1. Record a macro to change the font of the text in cell A1 to “Arial” and the font size to 12.
2. Modify the cell color to yellow.
Exercise 2:
Creating Variables and Displaying Values
1. Create a macro that declares a variable `name`.
2. Assign the value “John” to `name`.
3. Display the value of `name` in cell A1.
Sub ShowName()
Dim name As String
name = “John”
Range(“A1”).Value = name
End Sub
Exercise 3:
Writing a Function: Adding Two Numbers
1. Write a function called `AddNumbers` that takes two arguments, `num1` and `num2`.
2. The function should return the sum of these two numbers.
3. Use a macro to call this function and display the result in cell B1.
Function AddNumbers(num1 As Integer, num2 As Integer) As Integer
AddNumbers = num1 + num2
End Function
Sub DisplaySum()
Range("B1").Value = AddNumbers(5, 10)
End Sub
Prof. Khawla TADIST 1
Exercise 4:
Assigning Values to Multiple Cells
1. Create a macro that declares two variables, `text1` and `text2`.
2. Assign “Good Morning” to `text1` and “Good Evening” to `text2`.
3. Place `text1` in cell A1 and `text2` in cell A2.
Sub AssignValues()
Dim text1 As String
Dim text2 As String
text1 = "Good Morning"
text2 = "Good Evening"
Range("A1").Value = text1
Range("A2").Value = text2
End Sub
Exercise 5:
Simple Mathematical Operations in Macros
1. Create a macro that declares three variables: `price`, `quantity`, and `totalCost`.
2. Assign values to `price` (e.g., 50) and `quantity` (e.g., 3).
3. Calculate the total cost by multiplying `price` and `quantity` and store the result in
`totalCost`.
4. Display the `totalCost` in cell D1.
Sub CalculateTotalCost()
Dim price As Double
Dim quantity As Integer
Dim totalCost As Double
price = 50
quantity = 3
totalCost = price * quantity
Range("D1").Value = totalCost
End Sub
Prof. Khawla TADIST 2
Exercise 6:
Calculating the Area of a Rectangle
1. Create a macro that declares two variables, length and width.
2. Assign values to length (e.g., 5) and width (e.g., 10).
3. Write a function that calculates the area of the rectangle by multiplying length and
width.
4. Display the result in cell C1.
Prof. Khawla TADIST 3