Solved

vba find column number based on header value

Posted on 2014-10-22
5
4,516 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 31

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

Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

Join & Write a Comment

Drop Down List with Unique/Distinct Values (enhancing the Combo-Box with a few steps and a little code) David miller (dlmille) Intro Have you ever created a data validation list from a database field or spreadsheet column (e.g., Zip Codes or Co…
Introduction This Article is a follow-up to my Mappit! Addin Article (http://www.experts-exchange.com/A_2613.html), it was inspired by an email posting I made to EUSPRIG (http://www.eusprig.org/index.htm), I will briefly cover: 1) An overvie…
This Micro Tutorial will demonstrate in Google Sheets how to use the HYPERLINK function to create live links inside your spreadsheet.
This Micro Tutorial will demonstrate the scrolling table in Microsoft Excel using the INDEX function.

747 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

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now