Basic VBA Programs in Excel
1. Display a Message Box
Displays a simple message box with 'Hello, World!'
Sub HelloWorld()
MsgBox "Hello, World!"
End Sub
2. Input Box to Get User Input
Prompts the user to enter their name and then displays a greeting.
Sub GreetUser()
Dim userName As String
userName = InputBox("Enter your name:")
MsgBox "Hello, " & userName & "!"
End Sub
3. Loop Through a Range of Cells
Loops through cells in the range A1:A10 and sets each cell's value to 'Sample'.
Sub FillCells()
Dim i As Integer
For i = 1 To 10
Range("A" & i).Value = "Sample"
Next i
End Sub
4. Sum Two Numbers Using a Function
A function that takes two numbers as input and returns their sum.
Function AddNumbers(x As Double, y As Double) As Double
AddNumbers = x + y
End Function
5. Clear Contents of a Range
Clears the contents of the range B1:B10.
Sub ClearCells()
Range("B1:B10").ClearContents
End Sub
6. Conditional Statement with If...Then...Else
Checks if the value in cell A1 is greater than 50 and displays a message based on the result.
Sub CheckValue()
If Range("A1").Value > 50 Then
MsgBox "The value is greater than 50"
Else
MsgBox "The value is 50 or less"
End If
End Sub
7. Copy Data from One Cell to Another
Copies the content of cell A1 to cell B1.
Sub CopyData()
Range("B1").Value = Range("A1").Value
End Sub
8. Insert Data into the First Empty Row
Finds the first empty row in column A and inserts 'New Entry'.
Sub InsertInFirstEmptyRow()
Dim emptyRow As Long
emptyRow = Cells(Rows.Count, 1).End(xlUp).Row + 1
Cells(emptyRow, 1).Value = "New Entry"
End Sub
9. Display Current Date and Time in a Cell
Inserts the current date and time in cell A1.
Sub DisplayDateTime()
Range("A1").Value = Now
End Sub
10. Loop with Do...While
Uses a Do...While loop to set values in column A from row 1 until row 10 with the text 'Row #'
followed by the row number.
Sub DoWhileLoopExample()
Dim i As Integer
i = 1
Do While i <= 10
Range("A" & i).Value = "Row #" & i
i = i + 1
Loop
End Sub