IntroductionGetting StartedAll PostsNotesAbout The Author
cMatch And rMatch Functions
Friday, September 25, 2009 - 1:06 PM
These functions facilitate using the extremely useful built-in 'match' function to identify column or row numbers for a supplied header. These functions accomplish the same objective as using named ranges for each column, but in an easier and better way. Header names may also be stored as public variables in your declarations module to prevent typos.

These functions can be used to identify column and row numbers to use for filtering, assuming there are no empty column or row headers in the filter range. (Also see "Reliable Worksheet Filtering With VBA".) Check back soon for code to account for missing column and row headers.

You may prefer to hardcode the header row range name rather than using the FindRange function for sake of speed; or, if all of your sheets' headers are in the same row, then hard code the row number. That would improve speed, but using FindRange makes the functions more flexible.



Option Compare Text


Public Function cMatch&(ColHeader$, Optional ByVal WSName$, Optional ByVal WBName$, Optional ByVal HeaderRowNum&)
'returns column number for a given header (to avoid hardcoding same information)
'returns 0 if not found instead of an error
'using Option Compare Text

    On Error Resume Next
    If Not TestLen(WBName) Then WBName = ActiveWorkbook.Name
    If Not TestLen(WSName) Then WSName = Workbooks(WBName).ActiveSheet.Name
    If IsMissing(HeaderRowNum) Then
        Dim hdr As Range: hdr = FindRange("HeaderRow", WSName, WBName): HeaderRowNum = hdr.Row
    End If
    cMatch = Application.Match(ColHeader, Workbooks(WBName).Sheets(WSName).Rows(HeaderRowNum), 0)
End Function


Public Function rMatch&(RowHeader$, Optional ByVal WSName$, Optional ByVal WBName$, Optional ByVal HeaderColNum&)
'returns row number for a given header (to avoid hardcoding same information)
'returns 0 if not found instead of an error
'using Option Compare Text

    On Error Resume Next
    If Not TestLen(WBName) Then WBName = ActiveWorkbook.Name
    If Not TestLen(WSName) Then WSName = Workbooks(WBName).ActiveSheet.Name
    If IsMissing(HeaderRowNum) Then
        Dim hdr As Range: hdr = FindRange("HeaderColumn", WSName, WBName): HeaderColNum = hdr.Column
    End If
    cMatch = Application.Match(ColHeader, Workbooks(WBName).Sheets(WSName).Columns(HeaderColNum), 0)
End Function
<< Navigate to Friday, September 25, 2009 Add New Comment
No records found        
Add New Comment
Your name   
Subject   
Content   
*Required fields

January, 2009
February, 2009
March, 2009
April, 2009
May, 2009
June, 2009
July, 2009
August, 2009
September, 2009
October, 2009
November, 2009
December, 2009
IntroductionGetting StartedAll PostsNotesAbout The Author