Without a workbook I can only speculate. One of the issues with pivot items is that at least one of them must be selected at all times. So say you have four items A, B, C, D and only B is turned off. You want to turn B off and C on. So you write code to do this. If you turn B off before turning C on, you will get an error. Something like this might be happening with your code. I can't tell without seeing the data.

Generally, the way around this pitfall is to turn everything on, and then go back and selectively set what you want.