DonkeyOte,
Thanks for your code, it seems nice! However, when I used it the line
With PT: .AddDataField PT.PivotFields(strDate), "Sum of " & strDate
Activates only the new data field and deactivates the other..? And I have a PT with only one column. I don't know why this is happening though. Do you?
I think I can at the moment cope with the fact that I can only change one month at a time. But I would like it to be possible to change the date one month backwards. So I tried to solve this by using ChangeInMonths variable: if it is positive it works as your code and if it is negative it should add a new data field as a first column in a PT. If it is bigger than 31 code will produce an error message.
So this is when a new problem comes along.. how can I add a new data field in to the first column if the ChangeInMonths is negative..?
-John
Private Sub Worksheet_Change(ByVal Target As Range)
Dim Cell As Range, PT As PivotTable, strDate1 As String, Period As Range, ChangeInMonths As Integer, FirstDate As Range, Dtm As Range
Set Period = Range("Period")
Set FirstDate = Worksheets("Data").Range("FirstDate")
Set Dtm = Range("Date")
If Target.Count > 1 Or Intersect(Target, Dtm) Is Nothing Then Exit Sub
End If
If IsDate(Target.Value) Then
MsgBox "Vaihtuu"
ChangeInMonths = Dtm - FirstDate
MsgBox Abs(ChangeInMonths)
If Abs(ChangeInMonths) > 31 Then
MsgBox "You can change only one month forward or backward"
Exit Sub
End If
If ChangeInMonths >= 0 Then
strDate1 = Format(DateAdd("m", Period.Value - 1, Target.Value - Day(Target.Value) + 1), "MMM YYYY")
For Each Cell In Sheets("Data").Range("Dates")
Cell.Offset(1).Value = Format(Cell.Value, "MMM YYYY")
Next
Application.EnableEvents = False
Set PT = ActiveSheet.PivotTables("PivotTable3")
PT.PivotCache.Refresh
With PT: .AddDataField PT.PivotFields(strDate), "Sum of " & strDate, xlSum: End With
End If
If ChangeInMonths < 0 Then
strDate1 = Format(DateAdd("m", -1, Target.Value - Day(Target.Value) + 1), "MMM YYYY")
For Each Cell In Sheets("Data").Range("Dates")
Cell.Offset(1).Value = Format(Cell.Value, "MMM YYYY")
Next
Application.EnableEvents = False
Set PT = ActiveSheet.PivotTables("PivotTable3")
PT.PivotCache.Refresh
With PT: .AddDataField PT.PivotFields(strDate), "Sum of " & strDate, xlSum: End With
End If
End If
End Sub
Bookmarks