AWE_Sheet - Excel Automation, Simplified (Free)
Say Goodbye to Repetitive Coding and Hello to Streamlined Solutions
Are you tired of writing repetitive VBA code, memorizing cryptic syntax, and dealing with static columns that break your macros whenever the worksheet changes? Do you find yourself wondering if your code will fail without warning? It's time to leave those frustrations behind.
Introducing AWE_Sheet, a FREE, open-source VBA Class Module that transforms how you interact with Excel. With AWE_Sheet, you can:
- Eliminate repetitive coding: Simplify complex tasks into a few intuitive calls.
- Forget cryptic syntax: Use clear, readable code that’s easy to maintain.
- Handle dynamic columns effortlessly: Reference columns by name, regardless of their position, so your macros remain robust even when the worksheet changes.
- Gain confidence in your code's reliability: Built-in validations ensure your macros run smoothly without unexpected failures.
Moreover, AWE_Sheet allows you to step through the code using the editor or debugger, giving you a clear understanding of what's happening behind the scenes.
Say hello to a new world of coding solutions that are not only efficient but also transparent and easy to comprehend.
Experience the future of Excel automation with AWE_Sheet.
Quick Reference Guide
Functionality | Example |
---|---|
Initialize - Start Using AWE_Sheet Initialize internal and external worksheets in 5+ ways. |
' 1. Standard Initialization
|
Column Headers - Map Columns Easily set and map column headers for quick lookups. |
' Populate headers and data dynamically using an array
|
Cell Ranges - Locate and Retrieve Data Locate specific data dynamically in 6+ ways. |
' 1. Find Mary's age
|
Iterate Rows - Process All Rows Perform actions on each row in the DataBodyRange. |
' Loop through all rows
|
Filter - Find and Process Rows Apply filters and retrieve data from filtered rows dynamically. |
' 1. Clear existing filters
|
Lookups - Find and Process Rows Effortlessly locate rows using lookup criteria and perform actions. |
' Iterate through rows where Name = "John"
|
Sort Sheet - Multi-Column Sorting Sort rows based on one or more columns, either ascending or descending. |
' Sort rows by "Age" in ascending order and "Birthday" in descending order
|
Subsecond Updates - Bulk Processing Handle large datasets (up to 1M rows) with subsecond reads and updates. |
' Read contiguous columns ("Age" and "Birthday") into an array
|
Errors - Handle Errors Gracefully Catch and manage errors with built-in VBA error handling. |
' Handle initialization error for non-existent workbook
|
Sheet Boundaries - Range Locations Easily access headers, data ranges, and metadata dynamically. |
' Print the address of the header row
|
User Guide
Table of Contents
Initialization Function(s)
Initialize
Description
Prepares the AWE_Sheet object for workbook and worksheet operations. Validates inputs, initializes metadata for column mapping, and supports various targets (worksheets, sheet names, or ListObjects).
Parameters
Parameter | Type | Description |
---|---|---|
vTarget |
Variant | The target for initialization. The Variant can be:• String - Sheet name (e.g., "Sheet1" )• Worksheet - A worksheet object• ListObject - A table object (ListObject) |
lHdrRowNb |
Long | (Optional) The header row number. Defaults to 1 . |
vWBFullFileNmOrObj |
Variant | (Optional) Workbook reference. The Variant can be:• String - Full file path (e.g., "C:\Files\Workbook.xlsx" )• Workbook - A workbook object• Nothing - Defaults to ThisWorkbook if omitted |
bWBReadOnly |
Boolean | (Optional) Specifies whether to open the workbook in read-only mode. Defaults to False . |
Returns
Type | Description |
---|---|
Boolean | True if initialization succeeds; otherwise, raises an error. |
Error Handling
Error Name | Error Code | Description |
---|---|---|
WorkbookNotFound | 1001 | Workbook cannot be found. |
InvalidWorksheet | 1002 | Worksheet is missing or invalid. |
HeaderRowOutOfRange | 1003 | Header row number is out of range. |
SheetEmpty | 1006 | The worksheet is empty. |
InvalidTable | 1007 | The table (ListObject) is invalid. |
Notes
- Automatically maps columns if the worksheet has a valid header row.
- Supports handling empty worksheets and deferred workbook resolution.
- Works seamlessly with ListObjects for advanced table operations.
- If a workbook with the same name is already open, that workbook will be used instead of reopening it.
- Remove ":x:/r/" from SharePoint file paths to avoid opening the workbook in read-only mode.
Usage Examples
Sub Initialize_Examples() On Error GoTo ErrorHandler Dim mySheet As New AWE_Sheet ' Example 1: Initialize with a sheet name mySheet.Initialize "Sheet1" Debug.Print "Example 1: Initialization with sheet name successful!" ' Example 2: Initialize with a worksheet object Dim ws As Worksheet Set ws = ThisWorkbook.Sheets("DataSheet") mySheet.Initialize ws Debug.Print "Example 2: Initialization with worksheet object successful!" ' Example 3: Initialize with a ListObject (table) Dim tbl As ListObject Set tbl = ThisWorkbook.Sheets("DataSheet").ListObjects(1) mySheet.Initialize tbl Debug.Print "Example 3: Initialization with ListObject successful!" ' Example 4: Initialize with a custom header row mySheet.Initialize "DataSheet", 3 Debug.Print "Example 4: Initialization with custom header row successful!" ' Example 5: Initialize with a workbook object Dim wb As Workbook Set wb = Workbooks("Workbook.xlsx") mySheet.Initialize "Sheet1", 1, wb Debug.Print "Example 5: Initialization with workbook object successful!" ' Example 6: Initialize in read-only mode with an external workbook mySheet.Initialize "Sheet1", 1, "C:\Files\Workbook.xlsx", True Debug.Print "Example 6: Initialization in read-only mode successful!" ' Example 7: Initialize with an external workbook (file path) mySheet.Initialize "DataSheet", 1, "C:\Files\Workbook.xlsx" Debug.Print "Example 7: Initialization with external workbook successful!" ' Example 8: Initialize with a SharePoint workbook mySheet.Initialize "Data", 1, "https://sharepoint.com/sites/mysite/Documents/Workbook.xlsx" Debug.Print "Example 8: Initialization with SharePoint workbook successful!" ' Exit before error handler Exit Sub ErrorHandler: Debug.Print "Error during initialization: " & Err.Description Err.Clear End Sub
Column and Range Functions
ColumnNbr
Description
Retrieves the column number for a specified column name.
Parameters
Parameter | Type | Description |
---|---|---|
colName |
String | The name of the column to retrieve. |
Returns
Type | Description |
---|---|
Long | The corresponding column number. |
Notes
- Raises an error if the specified column name is not found in the header mapping.
Usage Examples
Sub ColumnNbr_Example() Dim mySheet As New AWE_Sheet ' Initialize with a worksheet mySheet.Initialize "Sheet1" ' Retrieve the column number for "Name" Debug.Print "Column number for 'Name': " & mySheet.ColumnNbr("Name") End Sub
ColumnRng
Description
Combines one or more specified columns into a single range.
Parameters
Parameter | Type | Description |
---|---|---|
columnNames() |
ParamArray | List of column names to combine. |
Returns
Type | Description |
---|---|
Range | A single combined range for all specified columns. |
Notes
- Raises an error if any of the column names are not found in the header mapping.
Usage Examples
Sub ColumnRng_Example() Dim mySheet As New AWE_Sheet ' Initialize with a worksheet mySheet.Initialize "Sheet1" ' Combine ranges for "Name" and "Age" Dim combinedRange As Range Set combinedRange = mySheet.ColumnRng("Name", "Age") Debug.Print combinedRange.Address End Sub
DataBodyRange
Description
Retrieves the data range of the worksheet, excluding the header row.
Parameters
This function does not take any parameters.
Returns
Type | Description |
---|---|
Range | The Excel range representing the data body. |
Notes
- Returns the ListObject DataBodyRange if the worksheet contains a valid table.
- Dynamically constructs a range based on the header row, last row, and last column if no ListObject is found.
Usage Examples
Sub DataBodyRange_Example() Dim mySheet As New AWE_Sheet ' Initialize with a worksheet mySheet.Initialize "Sheet1" ' Retrieve the data body range Debug.Print mySheet.DataBodyRange.Address End Sub
HeaderRowNbr
Description
Retrieves the header row number for the initialized worksheet.
Parameters
This function does not take any parameters.
Returns
Type | Description |
---|---|
Long | The header row number. |
Usage Examples
Sub HeaderRowNbr_Example() Dim mySheet As New AWE_Sheet ' Initialize with a worksheet mySheet.Initialize "Sheet1" ' Get the header row number Debug.Print mySheet.HeaderRowNbr End Sub
HeaderRowRng
Description
Retrieves the range of the header row for the initialized worksheet.
Parameters
This function does not take any parameters.
Returns
Type | Description |
---|---|
Range | The Excel range object representing the header row. |
Usage Examples
Sub HeaderRowRng_Example() Dim mySheet As New AWE_Sheet ' Initialize with a worksheet mySheet.Initialize "Sheet1" ' Get the header row range Debug.Print mySheet.HeaderRowRng.Address End Sub
LastColumnNbr
Description
Retrieves the last populated column in the worksheet.
Parameters
This function does not take any parameters.
Returns
Type | Description |
---|---|
Long | The column number of the last populated column. |
Usage Examples
Sub LastColumnNbr_Example() Dim mySheet As New AWE_Sheet ' Initialize with a worksheet mySheet.Initialize "Sheet1" ' Get the last column number Debug.Print mySheet.LastColumnNbr End Sub
LastRowNbr
Description
Retrieves the last populated row in the worksheet, considering data and header rows.
Parameters
This function does not take any parameters.
Returns
Type | Description |
---|---|
Long | The row number of the last populated row. |
Usage Examples
Sub LastRowNbr_Example() Dim mySheet As New AWE_Sheet ' Initialize with a worksheet mySheet.Initialize "Sheet1" ' Get the last row number Debug.Print mySheet.mySheet.LastRowNbr End Sub
Search and Sort Functions
FilterSheetBy
Description
Filters the worksheet by a specified column and value, hiding rows that do not match the criteria.
Parameters
Parameter | Type | Description |
---|---|---|
ColumnName |
String | The column header to filter on. |
Criteria |
Variant | The value to filter for. |
Returns
Type | Description |
---|---|
Boolean | True if the filter is applied successfully. |
Error Handling
Error Name | Error Code | Description |
---|---|---|
ColumnNotFound | 1008 | Column header not found in the worksheet. |
Usage Examples
Sub FilterSheetBy_Example() Dim mySheet As New AWE_Sheet mySheet.Initialize "Sheet1" mySheet.FilterSheetBy "Status", "Completed" End Sub
GetCellRng
Description
Retrieves the cell range (as a Range object) based on a row number and column header name.
Parameters
Parameter | Type | Description |
---|---|---|
RowNbr |
Long | The row number of the cell to retrieve. |
ColumnName |
String | The column header name of the cell to retrieve. |
Returns
Type | Description |
---|---|
Range | A Range object pointing to the specified cell. |
Error Handling
Error Name | Error Code | Description |
---|---|---|
ColumnNotFound | 1008 | The column header was not found in the worksheet. |
RowOutOfRange | 1009 | The row number is outside the range of the worksheet. |
Usage Examples
Sub GetCellRng_Example() Dim mySheet As New AWE_Sheet mySheet.Initialize "Sheet1" ' Retrieve the cell in row 2, column "Status" Dim cell As Range Set cell = mySheet.GetCellRng(2, "Status") Debug.Print "Cell Value: " & cell.Value End Sub
LookupColumnNbr
Description
Retrieves the column number associated with a specific header name. This function is case-insensitive and searches for an exact match.
Parameters
Parameter | Type | Description |
---|---|---|
HeaderName |
String | The name of the column header to look up. |
Returns
Type | Description |
---|---|
Long | The column number of the specified header, or raises an error if the header is not found. |
Error Handling
Error Name | Error Code | Description |
---|---|---|
ColumnNotFound | 1008 | The specified column header was not found. |
Usage Examples
Sub LookupColumnNbr_Example() Dim mySheet As New AWE_Sheet mySheet.Initialize "Sheet1" ' Retrieve the column number for the "Status" header Dim colNum As Long colNum = mySheet.LookupColumnNbr("Status") Debug.Print "Column Number: " & colNum End Sub
LookupRowNbrs
Description
Finds all row numbers where a specified column matches a given value.
Parameters
Parameter | Type | Description |
---|---|---|
ColumnName |
String | The column header to search in. |
Criteria |
Variant | The value to search for. |
Returns
Type | Description |
---|---|
Collection | A collection of row numbers where the criteria match. |
Error Handling
Error Name | Error Code | Description |
---|---|---|
ColumnNotFound | 1008 | Column header not found in the worksheet. |
Usage Examples
Sub LookupRowNbrs_Example() Dim mySheet As New AWE_Sheet mySheet.Initialize "Sheet1" ' Find all rows where "Status" is "Completed" Dim rowNumbers As Collection Set rowNumbers = mySheet.LookupRowNbrs("Status", "Completed") ' Iterate through found rows Dim row As Variant For Each row In rowNumbers Debug.Print "Found row: " & row Next row End Sub
SortSheet
Description
Sorts the worksheet by one or more columns in ascending or descending order.
Parameters
Parameter | Type | Description |
---|---|---|
ColumnNames |
Array | An array of column headers to sort by. |
SortOrders |
Array | (Optional) An array of sort orders corresponding to each column (asc or desc ). |
Returns
Type | Description |
---|---|
Boolean | True if sorting is applied successfully. |
Error Handling
Error Name | Error Code | Description |
---|---|---|
ColumnNotFound | 1008 | One or more column headers not found in the worksheet. |
Usage Examples
Sub SortSheet_Example() Dim mySheet As New AWE_Sheet mySheet.Initialize "Sheet1" mySheet.SortSheet Array("Status", "Priority"), Array("asc", "desc") End Sub
Error Handling
Error Handling Examples
Description
This example highlights AWE_Sheet's error-handling capabilities, showcasing two flexible strategies: propagating errors for centralized debugging or managing them locally for self-contained workflows. The goal is to ensure predictable operations and robust recovery in diverse scenarios.
Error Handling Strategies
This example demonstrates two approaches to error handling:
- Propagating Errors: Raising errors to be handled by the calling function, useful for debugging and centralized error management.
- Local Handling: Managing errors within the same function to allow the program to continue running despite encountering issues.
AWE_SheetError Constants
The `AWE_SheetError` constants represent specific error conditions that may occur during AWE_Sheet operations. Handling these constants allows for precise and meaningful error management. Key constants include:
WorkbookNotFound
: Triggered when the specified workbook cannot be located.InvalidWorksheet
: Indicates that the targeted worksheet is missing or invalid.ColumnNotFound
: Occurs when a specified column is not present in the header row.- See the ErrorHandler in the below code example for a complete list of AWE_Sheet errors and definitions.
Usage Scenarios
The following examples demonstrate:
- Initializing an AWE_Sheet with a worksheet and applying filters to retrieve data.
- Using lookups to access specific data rows based on criteria.
- Handling errors that may arise during these operations, with options to propagate or locally manage them.
Usage Examples
Sub ErrorHandling_Examples() On Error GoTo ErrorHandler Dim rng As Range ' Example 1: Initialize AWE_Sheet with a worksheet Dim mySheet As New AWE_Sheet mySheet.Initialize "SheetWithData" ' Example 2: Apply a filter and process rows where "Name" is "John" mySheet.ClearSheetFilters mySheet.FilterSheetBy "Name", "John" For Each rng In mySheet.DataBodyRange.SpecialCells(xlCellTypeVisible) Debug.Print mySheet.GetCellRng(rng, "Name").Value Debug.Print mySheet.GetCellRng(rng, "Age").Value Next rng mySheet.ClearSheetFilters ' Example 3: Retrieve and print data using lookups where "Name" is "John" Dim iRow As Variant For Each iRow In mySheet.LookupRowNbrs("Name", "John") Debug.Print mySheet.GetCellRng(iRow, "Name").Value Debug.Print mySheet.GetCellRng(iRow, "Age").Value Next iRow ' Example 4: Initialize AWE_Sheet with a ListObject. Apply filter and process rows where "Name" is "John" (table) Dim myTableSheet As New AWE_Sheet myTableSheet.Initialize ThisWorkbook.Worksheets("SheetWithTable").ListObjects(1) myTableSheet.FilterSheetBy "Name", "John" For Each rng In myTableSheet.DataBodyRange.SpecialCells(xlCellTypeVisible) Debug.Print myTableSheet.GetCellRng(rng, "Name").Value Debug.Print myTableSheet.GetCellRng(rng, "Age").Value Next rng myTableSheet.ClearSheetFilters Exit Sub ' ErrorHandler demonstrates two strategies for managing errors: ' 1. Propagate errors to the parent function for debugging using Err.Raise. ' 2. Handle errors locally within this function using Select Case and AWE_SheetError constants. ErrorHandler: ' Strategy 1: Propagate the error to the parent function ' Uncomment the next line to raise the error and stop execution here ' Err.Raise Err.Number, "ErrorHandling_Examples -> " & Err.Source, Err.Description ' Strategy 2: Handle errors within this function Select Case Err.Number ' Initialization Errors Case AWE_SheetError.WorkbookNotFound Debug.Print "Error during initialization: Workbook not found. Check the file path or ensure it is open." Case AWE_SheetError.InvalidWorksheet Debug.Print "Error during initialization: Worksheet is missing or invalid. Verify the sheet name." Case AWE_SheetError.HeaderRowOutOfRange Debug.Print "Error during initialization: The specified header row is out of range. Check the input row number." Case AWE_SheetError.SheetEmpty Debug.Print Warning: "The worksheet is empty or contains no usable data. Continuing operations." Resume Next Case AWE_SheetError.InvalidTable Debug.Print "Error during table initialization: ListObject (table) is invalid or not found. Ensure the table exists." ' Lookup and Column Errors Case AWE_SheetError.ColumnNotFound Debug.Print "Error: Column not found. Verify the column name in the header row." Case AWE_SheetError.NoMatch Debug.Print "Error: No matching rows found for the given criteria." Case AWE_SheetError.InvalidCriteria Debug.Print "Error: Invalid criteria provided. Check the search value or data type." Case AWE_SheetError.MetadataInitializationError Debug.Print "Error: Column mapping or metadata is incomplete. Ensure proper initialization." ' Filter and Sort Errors Case AWE_SheetError.ProtectedWorksheet Debug.Print "Error: Worksheet is protected. Unprotect the sheet to perform this operation." Case AWE_SheetError.FilterCriteriaMismatch Debug.Print Warning: "Filter criteria do not match any data. Execution will continue." Resume Next ' Default: Unexpected Errors Case Else Debug.Print "Unexpected Error: " & Err.Description & " (Error Code: " & Err.Number & ")" End Select ' Clear the error state Err.Clear End Sub