Create if then formula with ranges as values

2019-08-20 00:35发布

I have a pivot table I wanted to dynamically analyze with an if then formula. I created two ranges based on my criteria. The ranges are selected cells in my desired pivot field.

For instance, for Range1 I have it find the pivot field, move down one, and then select that as the range.

My formula looks like this and works, but what shows up in the formula is

 =if(myrange > .6%, myrange2, "")

and not the actual values.

The other problem I fear is that the two ranges with stay static and not move down when I try and auto fill more values.

Here is my code

 Sub blah()
    Dim pt As PivotTable
    Set pt = ActiveSheet.PivotTables(1)

    'range1

    pt.ColumnRange.Find("jack").Select
    Selection.Offset(1, 0).Select
    Dim myrange As range
    Set myrange = Selection
    MsgBox myrange

    'range2

    pt.RowRange.Find("steve").Select
    Selection.Offset(1, 0).Select
    Dim myrange2 As range
    Set myrange2 = Selection
    MsgBox myrange & myrange2

    'where i want the formula to go

    pt.ColumnRange.End(xlToRight).Select
    Selection.Offset(1, 0).Select
    Selection.End(xlToLeft).Select
    Selection.Offset(1, 0).Select
    Selection.Offset(0, 1).Select

    'formula

    ActiveCell.FormulaR1C1 = "myrange>0.3%,myrange2,"""")"

    'this part doesnt work but i'd like it to autofill to the end of the pivot

    Selection.AutoFill Destination:=range("P7:P36588")
    End Sub

2条回答
唯我独甜
2楼-- · 2019-08-20 01:24

I don't understand one thing:

if you already know that the formula will be in range "P7:P36588" why do you need all this code to find the cell where you want to write the formula?

Sub blah()
Dim pt As PivotTable
Set pt = ActiveSheet.PivotTables(1)

'range1
Dim myrange As range
Set myrange = pt.ColumnRange.Find("jack").Offset(1, 0)
MsgBox myrange

'range2
Dim myrange2 As range
Set myrange2 =  pt.RowRange.Find("steve").Offset(1, 0)
MsgBox myrange & myrange2

'formula
 frml = "=if(" & myrange.Address(0,0) & ">0.3%," & myrange2.Address(0,0) & ","""")"

'where i want the formula to go
pt.ColumnRange.End(xlToRight).Offset(1, 0).End(xlToLeft).Offset(1,1).Formula = frml

ActiveSheet.range("P7:P36588").Filldown
End Sub
查看更多
forever°为你锁心
3楼-- · 2019-08-20 01:30

You really should cut down on the selecting. you could for example do:

'range 1
Dim myrange As Range
Set myrange = pt.ColumnRange.Find("jack").Offset(1, 0)
MsgBox myrange

I'm pretty sure there is a shorter route to get to the desired range than this:

pt.ColumnRange.End(xlToRight).Select
Selection.Offset(1, 0).Select
Selection.End(xlToLeft).Select
Selection.Offset(1, 0).Select
Selection.Offset(0, 1).Select

Also, your formula is missing something.

 ActiveCell.FormulaR1C1 = "=if(myrange>0.3%,myrange2,"""")"

And instead of Autofill i would use something like this:

Range("P7:P36588").FormulaR1C1 = ActiveCell.FormulaR1C1
查看更多
登录 后发表回答