Consulting

Results 1 to 2 of 2

Thread: Reference to header instead of hardcoding column letter?

  1. #1

    Reference to header instead of hardcoding column letter?

    Hi all, Instead of hardcoding "G", "E", and "F", is there a way to make the VBA codes to use the headers? For example, The header for G is apple, E is orange, and F is banana. [ CODE ] Dim iFor i = 2 To Cells(Rows.Count, "A").End(xlUp).Row Cells(i, "G").Value = Cells(i, "E").Value & " " & Cells(i, "F").ValueNext i[ /CODE ]
    Last edited by doctortt; 11-26-2013 at 08:26 AM.

  2. #2
    VBAX Sage
    Joined
    Apr 2007
    Location
    United States
    Posts
    8,717
    Location
    The best way I've found for a general purpose method is to have a simple function return the column number. You could have it return the range also, but I think the number is more flexible

    Option Explicit
    Function ColNum(ColHeader As String, Optional WS As String = vbNullString) As Long
        Dim wsHeaders As Worksheet
        
        If Len(WS) = 0 Then
            Set wsHeaders = ActiveSheet
        Else
            Set wsHeaders = Worksheets(WS)
        End If
        
        ColNum = 0
        On Error Resume Next
        ColNum = Application.WorksheetFunction.Match(ColHeader, wsHeaders.Rows(1), 0)
        On Error GoTo 0
    End Function
    
    
     
    Function ColNumR(ColHeader As String, Optional WS As String = vbNullString) As Range
        Dim wsHeaders As Worksheet
        
        If Len(WS) = 0 Then
            Set wsHeaders = ActiveSheet
        Else
            Set wsHeaders = Worksheets(WS)
        End If
        
        Set ColNumR = Nothing
        On Error Resume Next
        Set ColNumR = wsHeaders.Columns(Application.WorksheetFunction.Match(ColHeader, wsHeaders.Rows(1), 0))
        On Error GoTo 0
    End Function
    
     
    
    
    Sub test()
        Dim r As Range
        
    '    MsgBox ColNum("AAA")            ' 1
    '    MsgBox ColNum("AAA", "Sheet1")              '1
    '    MsgBox ColNum("NOT THERE")              '0
        Set r = ActiveSheet.Columns(ColNum("CCC"))
        MsgBox r.Address                       ' $C:$C
    End Sub

    Paul

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •