vba vlookup formula based on column heading?

I need to enter the formula in the last empty cell and copy down. However, I now realize that the E2 & M2 in my formula, which represents weight and a integer - may be in different columns! Can I find them based on the column header?? It will be the only thing certain to be the same. HELP!??

Sub GroundRating()
Application.ScreenUpdating = False
    Dim NextCol As Long, LastRow As Long
    With Filtered_Data
        NextCol = .Cells(1, Columns.Count).End(xlToLeft).Column + 1
        LastRow = .Cells(Rows.Count, "A").End(xlUp).Row
        .Cells(1, NextCol) = "Ground Rates"
        .Range(.Cells(2, NextCol), .Cells(LastRow, NextCol)).Formula = "=IF($E2>=150,(VLOOKUP($E2,GR,$M2,TRUE)/150)*$E2,VLOOKUP($E2,GR,$M2,FALSE))"
    End With
    
    Application.ScreenUpdating = True
End Sub

Open in new window

sample-ground-formula.xlsx
Euro5Asked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Euro5Author Commented:
This is what I'm trying now, but code stopping.

Sub GroundRating()
Application.ScreenUpdating = False
    Dim NextCol As Long, LastRow As Long
    With Filtered_Data
        NextCol = .Cells(1, Columns.Count).End(xlToLeft).Column + 1
        LastRow = .Cells(Rows.Count, "A").End(xlUp).Row
        .Cells(1, NextCol) = "Ground Rates"
        .Range(.Cells(2, NextCol), .Cells(LastRow, NextCol)).Formula = "=IF(vlookup(MATCH(""Rated Weight"",$A$1:NextCol,0)>=150,VLOOKUP(MATCH(""Rated Weight"",$A$1:NextCol,0),GR,MATCH(""Zone"",$A$1:NextCol),TRUE)/150)*MATCH(""Rated Weight"",$A$1:NextCol,0),VLOOKUP(MATCH(""Rated Weight"",$A$1:NextCol,0),GR,MATCH(""Zone"",$A$1:NextCol,0),FALSE))"
    End With
    
    Application.ScreenUpdating = True
End Sub

Open in new window

0
Glenn RayExcel VBA DeveloperCommented:
This code will work:
Option Explicit
Sub GroundRating()
    Application.ScreenUpdating = False
    Dim NextCol As Long, LastRow As Long
    Dim Filtered_Data As Range
    Set Filtered_Data = Range("A1:N1000")
    
    Dim HRow As Range
    Dim cl As Object
    Dim RWt, Zn As String
    Set HRow = Range("A1", Range("A1").End(xlToRight))
    For Each cl In HRow
        Select Case cl.Value
            Case "Rated Weight"
                RWt = Left(cl.EntireColumn.Address, InStr(1, cl.EntireColumn.Address, ":") - 1)
            Case "Zn"
                Zn = Left(cl.EntireColumn.Address, InStr(1, cl.EntireColumn.Address, ":") - 1)
        End Select
    Next cl
    
    With Filtered_Data
        NextCol = .Cells(1, Columns.Count).End(xlToLeft).Column + 1
        LastRow = .Cells(Rows.Count, 1).End(xlUp).Row
        .Cells(1, NextCol) = "Ground Rates"
        .Range(.Cells(2, NextCol), .Cells(LastRow, NextCol)).Formula = _
            "=IF(" & RWt & "2>=150,(VLOOKUP(" & RWt & "2,GR," & Zn & "2,TRUE)/150)*" & RWt & _
            "2,VLOOKUP(" & RWt & "2,GR," & Zn & "2,FALSE))"
    End With
    
    Application.ScreenUpdating = True
End Sub

Open in new window


Lines 8-19 are the first change:  it scans through the header row for the two components for which you need to reference in your formula (Rated Weight and Zone) and assigns strings to the column address found.

Lines 25-28 is the revised compound formula that will refer to the correct columns.

The attached workbook has this code.  I've tested by moving the Zone column to a new location.

Regards,
-Glenn
EE-sample-ground-formula.xlsm
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Euro5Author Commented:
AHHHHH!!!!!! Bless you!!!  :)      Excellent solution!!
0
Big Business Goals? Which KPIs Will Help You

The most successful MSPs rely on metrics – known as key performance indicators (KPIs) – for making informed decisions that help their businesses thrive, rather than just survive. This eBook provides an overview of the most important KPIs used by top MSPs.

Glenn RayExcel VBA DeveloperCommented:
Glad I could help.  

Note that I did not include any error handling:  if either of your required columns are missing or misspelled, your formula will be in error.

Regards,
-Glenn
0
Euro5Author Commented:
Understood. I have a previous code that names these columns, so that they will always be exactly the same.
Thanks for thinking of that!
0
Euro5Author Commented:
I did have a problem that the range was too small, but I already closed the question, so I had to repost - in case you see that.
The range only went to column N, but the user may have more data - so I really need it dynamic.
But its a small fix...
0
[ fanpages ]IT Services ConsultantCommented:
Slightly easier on the eye...

Sub GroundRating()

  Dim intColumn_Rated_Weight                            As Integer
  Dim intColumn_Zone                                    As Integer
  Dim NextCol                                           As Long
  Dim LastRow                                           As Long
  Dim strFormula                                        As String
  
  intColumn_Rated_Weight = IIf(IsError(Application.WorksheetFunction.Match("Rated Weight", Worksheets("Sheet1").Rows(1&), 0)), _
                               0, _
                               Application.WorksheetFunction.Match("Rated Weight", Worksheets("Sheet1").Rows(1&), 0))
                               
  intColumn_Zone = IIf(IsError(Application.WorksheetFunction.Match("Zone", Worksheets("Sheet1").Rows(1&), 0)), _
                       0, _
                       Application.WorksheetFunction.Match("Zone", Worksheets("Sheet1").Rows(1&), 0))
  
  If intColumn_Rated_Weight > 0 And _
     intColumn_Zone > 0 Then
     strFormula = Replace("=IF($E2>=150,(VLOOKUP($E2,GR,$M2,TRUE)/150)*$E2,VLOOKUP($E2,GR,$M2,FALSE))", _
                          "$E2", _
                          Cells(2&, intColumn_Rated_Weight).Address(RowAbsolute:=False))
                          
     strFormula = Replace(strFormula, _
                          "$M2", _
                          Cells(2&, intColumn_Zone).Address(RowAbsolute:=False))
     
     Application.ScreenUpdating = False
     
     With Filtered_Data
          NextCol = .Cells(1, Columns.Count).End(xlToLeft).Column + 1
          LastRow = .Cells(Rows.Count, "A").End(xlUp).Row
         .Cells(1, NextCol) = "Ground Rates"
         .Range(.Cells(2, NextCol), .Cells(LastRow, NextCol)).Formula = strFormula
     End With
    
     Application.ScreenUpdating = True
  End If
  
End Sub

Open in new window

0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft Excel

From novice to tech pro — start learning today.