I have this problem that I can't solve, I'm writing an Excel Macro that build up a pivot table taking the data from a table. When a field in the table is 0 I don't want to perform the calculation of the calculated field and display a blank cell in the pivot table.

my conditional formula is this one:

=IF((field1=0),"",(field1/field2))

Putting this formula into VBA as follows

pt.CalculatedFields.Add Name:="ptfieldname", Formula:="=IF((field1=0),"",(field1/field2))"

display an empty pivot table, when I put the same formula in excel using the "Fields, Items & Set" button in the pivot table option tab goes well... so I think that the formula is right, but what I have to do to get it permorf well also within the VBA macro?!

thanks in advance

有帮助吗?

解决方案

Welcome to SO. I am pretty new here myself, but have found it very useful lately.

Anyway, here is your answer. I found it by using the Macro Recorder to see the exact syntax it uses when creating a calculated field in the pivot table. Hopefully the method of my finding the answer helps you find more answers on your own in the future.

The problem was in the way you referenced the formula in VBA. VBA needs to have actual quotes inside of quotes, so the

=IF((field1=0),"",(field1/field2)) 

in

pt.CalculatedFields.Add Name:="ptfieldname", Formula:="=IF((field1=0),"",(field1/field2))"

needs to be

=If(field1=0,"""",(field1/field2))
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top