简体   繁体   中英

VBA Lookup- lookup range error

I've exhausted every option so I'm left with throwing myself at your mercy. I'm trying to automate a report in excel but the lookup just isn't working. the idea is it does a lookup on a pivot table that is refreshed every day and moves along to the next empty day and gives the results. I've tried recording and the lookup works but each day it moves the look up range one column on and I can't get it to fix. My code is below, any help will be greatly appreciated.

   Range("B36").Select
    Selection.End(xlToRight).Select
    ActiveCell.Offset(0, 1).Select


  Dim row As Integer
    For i = 36 To 40


Set inRange = Range("B" & i & ":B" & i)
Set LookupRange = Sheets("MV Pivot").Columns("N:R")


MsgBox (inRange)

    ActiveCell.FormulaR1C1 = _
        "=IFERROR(VLOOKUP(" & inRange & "," & LookupRange & ",5,FALSE),0)"
                      ActiveCell.Offset(1, 0).Select
        Next I

Thanks

Logie143

Just a few things..

  1. As FAURILLOU Amandine mentioned, I think you can reference the inRange as Range("B" & i) - agreed.
  2. As Darren mentioned use formula - agreed.
  3. I would personally look at the pivot table, and try to reference the data range for the pivot, as opposed to reference it to. Just the way I would try to do it. That way if the location of the pivot changed you'll be fine. Had a very quick look at the object model and it would something like:

    Worksheets("MV Pivot").PivotTables("The Name").DataBodyRange

  4. Although you use a formula to lookup the pivot data column, you could actually call the Evaluate function. If you use your formula in the cell, if the pivot table data changes, it will also change the historical data since its a formula. You can get around this by simply hardcoding the result.

All of that being said, please give this a go and see if it works/fixes your issue.

Sub Test()

Range("B36").Select
Selection.End(xlToRight).Select
ActiveCell.Offset(0, 1).Select

Dim inRange As Range, LookupRange As Range
Dim row As Integer, i As Integer

For i = 36 To 40
    Set inRange = Range("B" & i)
    Set LookupRange = Range("$K$36:$P$41")
    MsgBox (inRange)
    ActiveCell.Formula = Evaluate("=IFERROR(VLOOKUP(" & inRange.Address & "," & LookupRange.Address & ",5,FALSE),0)")
    ActiveCell.Offset(1, 0).Select
Next i

End Sub

Hope that helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM