Solved

Assigning vlookup formula using vba

Posted on 2011-10-24
343 Views
Set BaseWks = Sheets("Summary Data")
Set PivotWks = Sheets("PivotTab")

lastrow = PivotWks.UsedRange.Rows.Count - PivotWks.UsedRange.Row

For n = 2 To lastrow
BaseWks.Cells(n, 5).Formula = (BaseWks.Cells(n, 6).Value) / (WorksheetFunction.VLookup(BaseWks.Cells(n, 3), PivotWks.Range("A2:B" & lastrow), 2, False))
Next n

Hi, I developed the above formula (so far) in an attempt to covert the excel formula to vba

``````=IF(VLOOKUP(C2,PivotTab!A2:B95,2,FALSE)<>"",F2/VLOOKUP(C2,PivotTab!A2:B95,2,FALSE),"No Data")
``````

As you can see, I've figured out the vlookup part (it works) and the division part. But putting the formula with 'IF' statement and as a live formula is been a problem so far.

When I say 'live' I want the formula to be there in the excel cell instead of just the value-result being displayed (which is whats happening now)

Any help is much appreciated!
0
Question by:Shanan212

LVL 43

Accepted Solution

You are mixing two things. The left of the = sign is looking for a formula whereas the right side of the = is returning only the value.

To return you need to assign the Excel syntax within quotes...

BaseWks.Cells(n, 5).Formula = "=IF(VLOOKUP(C2,PivotTab!A2:B95,2,FALSE)<>"""",F2/VLOOKUP(C2,PivotTab!A2:B95,2,FALSE),""No Data"")"
0

LVL 13

Author Comment

Thanks! That would work but how would I keep the formula dynamic (according to changing rows in the for loop)?

0

LVL 43

Expert Comment

change F2 to

If you need C2 to vary as well change it to

0

LVL 6

Expert Comment

Something like

BaseWks.Cells(n, 5).Formula = "=IF(VLOOKUP(C" & n & ",PivotTab!A2:B95,2,FALSE)<>'',F2/VLOOKUP(C" & n & ",PivotTab!A2:B95,2,FALSE),'No Data')"
0

LVL 33

Assisted Solution

Try this.
``````LookupRange = "'" & PivotWks.Name & "'!A2:B" & lastRow

BaseWks.Range("E2:E" & lastRow).Formula = "=IF(VLOOKUP(C2, " & LookupRange & ", 2,0) ="""",""No Data"", F2/VLOOKUP(C2," & LookupRange & ", 2,0))"
``````
0

LVL 13

Author Closing Comment

Thanks all!
0

Featured Post

Suggested Solutions

A2 = A1 That kind of cell reference is relative.  If you copy it from A2 to B2, then B2 will get this: B2 = B1 That's all fine and good, but if you then insert a new row above row 2, you'll find: A3 = A1 B3 = B1 This is intentional. …
Sparklines have been introduced with Excel 2010 and are a useful tool for creating small in-cell charts, used for example in dashboards. Excel 2010 offers three different types of Sparklines: Line, Column and Win/Loss. What it does not offer is a…
Viewers will learn the basics of slicers and timelines for both PivotTables and standard Excel tables in Excel 2013.
The viewer will learn how to create two correlated normally distributed random variables in Excel, use a normal distribution to simulate the return on different levels of investment in each of the two funds over a period of ten years, and, create a …