KD Jayakody

Call Us: 076 72 33 595

Excel VBA Macro Script to Search and Display Birthday Messages in a Specified Range of Cells

Mar 14, 2023

As a person who tried to master MACROS in excel, this is just an effort. I tried to make a excel sheet with birthdays of students and needed check if any birthdays are available for the date we run the script. By the way almost ok, but still need to optimize the code with a few scenarios.

The code provided is a VBA macro script for searching for birthdays in a specified range of cells in an Excel worksheet. The macro uses the IsDate function to check if each cell in the range contains a valid date value. If a valid date value is found, the macro checks if the month and date components of the value match the current month and date using the Month and Day functions. If a match is found, a message box is displayed with a personalized birthday message. If no birthdays are found that match the current month and date, a message box is displayed to indicate this.

Sub SearchBirthdays()
    Dim rng As Range
    Dim cel As Range
    Dim foundBirthdays As Boolean
    
    ' Set the range to search for birthdays
    Set rng = Range("B2:B100")
    
    ' Initialize the flag for found birthdays
    foundBirthdays = False
    
    ' Loop through each cell in the range
    For Each cel In rng
        ' Check if the cell contains a birthday
        If IsDate(cel.Value) Then
            ' If it does, check if it's today's date
            If Month(cel.Value) = Month(Date) And Day(cel.Value) = Day(Date) Then
                ' If it is, display a message box
                MsgBox "Happy birthday, " & cel.Offset(0, -1).Value & "!"
                foundBirthdays = True
            End If
        End If
    Next cel
    
    ' If no birthdays were found, show a message box
    If Not foundBirthdays Then
        MsgBox "No birthdays found."
    End If
End Sub

 

Recent Posts