Posted in

Excel VBA Coding, Macro Recording Examples — Free Download

Excel VBA Coding
Excel VBA Coding

Applying FluidStyle Revamp to Excel VBA content

Excel VBA coding offers flexibility for automating tasks, whether you’re scripting from scratch or refining existing code. While the Macro Recorder can generate code automatically, writing directly in the VBA editor unlocks deeper customization. For instance, instead of relying on recorded steps—which might include redundant actions—you can craft precise procedures tailored to your needs. Imagine creating a custom function like FillData within a new module. Here, comments (marked in green) act as notes to explain your logic without affecting execution, while reserved keywords (highlighted in blue) structure the code, such as Sub, End Sub, or Range, forming the foundation of VBA’s syntax.

Testing your code is straightforward with the editor’s toolbar: the play button runs the script, the pause button halts it temporarily, and the stop button terminates execution entirely. For smoother coding, leverage IntelliSense, a feature that pops up suggestions when you type a period after an object. This dropdown menu lists methods and properties, guiding you through Excel’s object hierarchy—a critical concept to grasp. Take the example of Cells(5, 3).Value, which retrieves data from row 5, column 3. Each dot in this chain navigates deeper into Excel’s structure, like drilling from a worksheet to a specific cell. Over time, these chains might grow complex, but pressing F1 on any keyword pulls up detailed help documentation, demystifying even the trickiest syntax.

The Macro Recorder still shines for repetitive tasks. To use it, navigate to the View tab, click Record Macro, and name your macro. You’ll also choose where to store it—either in the current workbook for project-specific use or in the Personal Macro Workbook for cross-file accessibility. As you perform actions in Excel, like formatting cells or building formulas, the recorder translates them into VBA code. Once finished, review the generated code to remove unnecessary steps. For example, a 10-step formatting process could be condensed into a single macro, saving time on future tasks.

However, recorded macros aren’t always efficient. They might include extra selections or default settings, which you can manually trim. Tweaking this code not only streamlines it but also helps you learn VBA’s logic. Saved macros reside in modules, which act as storage containers for reusable code. By organizing procedures here, you can easily copy them into new projects, turning one-time solutions into long-term tools.

If you encounter tangled object chains (like Workbook.Worksheet.Range.Value), break them into shorter lines using variables. This improves readability and reduces errors. For instance, assign Set ws = ThisWorkbook.Worksheets("Sheet1") to reference the worksheet once, then use ws.Range("A1") thereafter. This approach simplifies debugging and adapts well to larger projects.

Ultimately, blending manual coding with Macro Recording lets you automate Excel tasks efficiently. Whether you’re building macros from scratch or refining recorded ones, understanding VBA’s structure transforms repetitive work into seamless, one-click solutions.

1. Assigning Values and Formatting Cells Code

Sub EditCell()
    Range("A1").Value = "Hello World"     ' Write text to cell A1
    Range("A1").Font.Bold = True          ' Bold the text
    Range("A1").Interior.Color = RGB(255, 255, 0) ' Set background to yellow
    Range("A1").HorizontalAlignment = xlCenter    ' Center-align text
End Sub

What Does It Do?
Writes “Hello World” to cell A1, applies bold formatting, yellow background, and centers the text.

2. Macro Recorder-Generated Example Code

Sub RecordMacro()
    Range("B2").Select
    ActiveCell.FormulaR1C1 = "=RAND()"    ' Generate a random number
    Range("B2").Copy
    Range("C2").PasteSpecial Paste:=xlPasteValues ' Paste as value
End Sub

What Does It Do?
A basic macro-generated code: Adds a random number to B2 and pastes the value to C2.

3. InputBox for User Input Code

Sub GetUserInput()
    Dim userInput As String
    userInput = InputBox("Please enter text:", "Data Entry") ' Open InputBox
    
    If userInput <> "" Then
        Range("A3").Value = userInput    ' Write to A3 if input is not empty
    Else
        MsgBox "No data entered!", vbExclamation ' Warning message
    End If
End Sub

What Does It Do?
Prompts the user for text and writes it to A3. Displays a warning if no input is provided.

4. For Loop to Auto-Fill Rows Code

Sub FillRows()
    Dim i As Integer
    For i = 1 To 10
        Cells(i, 1).Value = i    ' Fill column 1 with numbers 1 to 10
    Next i
End Sub

What Does It Do?
Fills cells A1 to A10 with numbers 1 through 10.

5. Error Handling Code (On Error Resume Next)

Sub ErrorHandling()
    On Error Resume Next    ' Ignore errors
    Dim result As Double
    result = 10 / 0         ' Division by zero error
    
    If Err.Number <> 0 Then
        MsgBox "Error: " & Err.Description, vbCritical ' Show error message
        Err.Clear           ' Clear error
    End If
    On Error GoTo 0         ' Disable error handling
End Sub

What Does It Do?
Catches division-by-zero errors and alerts the user.

6. Worksheet_Change Event for Dynamic Control Code

Private Sub Worksheet_Change(ByVal Target As Range)
    If Not Intersect(Target, Range("A:A")) Is Nothing Then  ' If column A changes
        Target.Offset(0, 1).Value = Now()    ' Add timestamp to column B
    End If
End Sub

What Does It Do?
Adds a timestamp to column B when any cell in column A is modified.

7. Custom Function (UDF) for Tax Calculation Code

Function CalculateTax(Amount As Double) As Double
    CalculateTax = Amount * 0.18    ' Calculate 18% tax
End Function

How to Use?
In Excel, type =CalculateTax(100) to get a result of 18.

8. Conditional Logic (If-Else) with MsgBox Code

Sub CheckValue()
    Dim value As Double
    value = Range("C5").Value
    
    If value > 100 Then
        MsgBox "Value exceeds 100! Warning!", vbExclamation ' Alert
    Else
        MsgBox "Value is within normal range.", vbInformation    ' Info message
    End If
End Sub

What Does It Do?
Checks cell C5: Alerts if the value exceeds 100; otherwise, shows a confirmation.

Notes for Using the Code:

  1. Open the VBA editor in Excel with Alt + F11.
  2. Insert a new module and paste the code.
  3. Run macros via Alt + F8.

Hi! I'm Ashley McKinnel. I was born in New York City in 1989. I make websites and also write articles for software promotions. I've written dozens of articles for the 3 most popular sites in the US and they've gotten a lot of attention. I create pages with technical information about downloading, installing and uninstalling software. I research new games and their compatible patches, and I also turn the photos I take for myself into images and digital downloads. I'm here now so that I can continue to do work that can be useful. I think you'll be satisfied when you read my articles. That's why I enjoy working for you. I hope to produce more things for you.