Getting Cell Value from a range based on Column Name

I have a requirement to change the following code to this:


'in a loop with a being rownumber     
CurrInvoiceNum = ws2.Range("B" & a).Value


' Transaction ID is the column name of B and the reason for the change is that it need not always be in B.
CurrInvoiceNum = ws2.Range("Transaction ID" & a).Value 

I tried getting cells like this:

Cells.Find(What:="Transaction ID", LookAt:=xlWhole).Column ) 

but could not make it use of the rownumber..



First approach - using Application.Match (faster one):

Dim colNum

With ws2
    colNum = Application.Match("Transaction ID", .Range("1:1"), 0)
    If IsError(colNum) Then
        MsgBox "Column with header 'Transaction ID' not found"
        Exit Sub
    End If

    CurrInvoiceNum = .Cells(a, colNum).Value
End With

Second approach - using .Find:

Dim rng As Range

With ws2
    Set rng = .Range("1:1").Find(What:="Transaction ID", LookAt:=xlWhole)
    If rng Is Nothing Then
        MsgBox "Column with header 'Transaction ID' not found"
        Exit Sub
    End If

    CurrInvoiceNum = .Cells(a, rng.Column).Value
End With

both apporaches assumes that your headers are in first row: .Range("1:1")

This assumes that the column name is in the first row:

Sub dural()
    Set r = Rows(1).Find(What:="Transaction Id")
    a = 7
    CurrInvoiceNum = r.Offset(a - 1, 0).Value
End Sub

Need Your Help

sorting flash overlap problem wmode='opaque'

php flash video wmode param

im trying to fix the flash overlap using regular expressions. here is an example of markup im trying to convert to my needs

Join 2 non existing tables in MYSQL

mysql join

I'm having trouble joining two tables that come from two queries, meaning I don't have the actual table in my database. I have the following: