views:

380

answers:

3

I'm generating a pivot chart in Excel 2002 with a macro, using a date field as the chart report filter (setting the field orientation to xlPageField). I would like to set the default selected value of this pivotfield to the most recent value in the date field. What's the right syntax for doing that in VBA?

A: 

Don't you just want to select the cell after you have dynamically created the chart?

Something like:

Dim value As Date
value = "1-apr-09"
Dim row As Integer
row = 0

Dim keeplooping As Boolean
keeplooping = True
While (keeplooping)
    row = row + 1
    If Range("B" & row).value = value Then
        keeplooping = False
        Range("B" & row).Select
        MsgBox ("found it")
    ElseIf Range("B" & row).value = "" Then
        keeplooping = False
        MsgBox ("Not found")
    End If
Wend
Christian Payne
A: 

chartObject.PivotLayout.PivotTable.PivotFields("fieldName").CurrentPage = "fieldValue"

That's from Excel 2003 but I presume 2002 will be similar

barrowc
Yes, you're right, but what I really wanted to calculate in VBA is the "fieldValue". I've solved my problem by creating a separate sql query to find the maximum date value but I was wondering how I could have done that by just querying the pivot table
TheObserver
A: 

Can't you loop through all the items for that pagefield? Here's for a pivot table but getting it to work for a chart shouldn't be big deal:

Sub Main()
    Dim pvt As PivotTable
    Dim fld As PivotField
    Dim itm As PivotItem
    Dim m As Variant

    Set pvt = Worksheets(1).PivotTables(1)
    Set fld = pvt.PageFields(1)

    m = fld.PivotItems(1)
    For Each itm In fld.PivotItems
        If itm.Value > m Then m = itm.Value
    Next itm

    fld.CurrentPage = m
End Sub
Bart Willems
My alternative was to get the most recent date with an SQL query
TheObserver