我有一个数据透视表,我想用if then公式动态分析。我根据我的标准创建了两个范围。范围是我所需的枢轴字段中的选定单元格。
例如,对于Range1,我找到了pivot字段,向下移动了一个,然后选择它作为范围。
我的公式看起来像这样并且有效,但公式中显示的是
=if(myrange > .6%, myrange2, "")
而不是实际值。
我担心的另一个问题是当我尝试自动填充更多值时,两个范围保持静止而不会向下移动。
这是我的代码
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
答案 0 :(得分:1)
我不明白一件事:
如果你已经知道公式将在范围内" P7:P36588"你为什么需要所有这些代码来找到你想要写公式的单元格?
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
答案 1 :(得分:0)
你真的应该减少选择。 你可以这样做:
'range 1
Dim myrange As Range
Set myrange = pt.ColumnRange.Find("jack").Offset(1, 0)
MsgBox myrange
我非常确定到达所需范围的路线比此更短:
pt.ColumnRange.End(xlToRight).Select
Selection.Offset(1, 0).Select
Selection.End(xlToLeft).Select
Selection.Offset(1, 0).Select
Selection.Offset(0, 1).Select
另外,你的公式遗漏了一些东西。
ActiveCell.FormulaR1C1 = "=if(myrange>0.3%,myrange2,"""")"
而不是Autofill,我会使用这样的东西:
Range("P7:P36588").FormulaR1C1 = ActiveCell.FormulaR1C1