Solved

vba find column number based on header value

Posted on 2014-10-22
5
5,028 Views
Last Modified: 2014-10-22
I wondering if there is a way I can get the column number based on a header value in row 1.   I am currently looping through  columns but the columns keep moving in the file that is being used.   The below is a sample of the code but instead defining it as column 5, I would like to find Customer Lead in row 1 and then get the column number.

WS.Range("D8").Value = wsData.Cells(i, 5).Value    'Customer Lead 

Open in new window


Thanks,
Montrof
0
Comment
Question by:montrof
  • 3
5 Comments
 
LVL 32

Accepted Solution

by:
Rob Henson earned 500 total points
ID: 40396703
You can use the worksheet function MATCH within a VBA script to get the column number:

ColOffset = Application.WorksheetFunction.MATCH("Customer Lead",Sheet1!$1:$1,0)

Thanks
Rob H
0
 
LVL 1

Author Closing Comment

by:montrof
ID: 40396718
Thank you very much

Montrof
0
 
LVL 1

Author Comment

by:montrof
ID: 40396735
Sorry one more question is there an easy way to skip the search if the value is not found.
0
 
LVL 33

Expert Comment

by:Norie
ID: 40396774
If the header might not be there you could try something like this.
Dim Res As Variant 

    Res = Application.Match("Customer Lead", Sheets("Sheet1").Rows(1), 0)

    If IsError(Res) Then 
        MsgBox "Customer Lead column not found."
        Exit Sub
    End If
    
     ' continue with code
    WS.Range("D8").Value = wsData.Cells(i, Res).Value

Open in new window

0
 
LVL 1

Author Comment

by:montrof
ID: 40397007
Thanks Again
0

Featured Post

ScreenConnect 6.0 Free Trial

Discover new time-saving features in one game-changing release, ScreenConnect 6.0, based on partner feedback. New features include a redesigned UI, app configurations and chat acknowledgement to improve customer engagement!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

INDEX and MATCH can be used to great effect to replace HLOOKUP and VLOOKUP as it does not have the limitation of needing the data to be sorted so that the reference value is in the first column or row. It also has the ability to perform a bi-directi…
This tutorial explains how to create a series of drop-down lists that are dependent upon prior selections to guide (“force”) the user to make the correct selection and reduce data errors within Microsoft Excel. Excel 2010 was used for this tutorial;…
This Micro Tutorial demonstrate the bugs in Microsoft Excel for Mac with Pivot Charts.
This Micro Tutorial will demonstrate in Microsoft Excel how to add style and sexy appeal to horizontal bar charts.

810 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question