I am using Delphi to write a program which builds a Pivot Table. Because I want to use Distinct Count, I have to 'Add to Data Model', which apparently creates an OLAP cube in the background. This means that I cannot use the "normal" Excel_TLB unit, but instead have to use the GetActiveOLE based routines...
I can connect, I can build the data model, I can create the pivot cache and pivot table object, but when I go to add the fields to the Pivot, I get an error at runtime, normally 'Member not Found'.
When I step through my code, after I create the PivotTable object, I can go to excel, and I see the list of possible columns for my pivot table. They are listed under a 'Range' level. (Which is what I would expect when you 'Add to Data Model' for a pivot). When I turn on record Macro, and manually add the field (category) to the filter section, the VBA code looks like this...
With ActiveSheet.PivotTables("PivotTable1").CubeFields("[Range].[Category]")
.Orientation = xlPageField
.Position = 1
End With
Below is my Delphi Code. It is the last commented lines which do NOT work.
procedure Build_Pivot;
var
// Connection Info
SheetName: String;
ConnRange, ConnName, ConnString, ConnCommand: String;
ConnPath, ConnFile : String;
ConnCount : Integer;
XLApp: Variant;
gConnection: Variant;
// Now define variables for the Pivot
myPivotCache: Variant;
myPivotTable: Variant;
StartCellRange: Variant;
fFilter1, fFilter2: Variant;
begin
XLApp := GetActiveOleObject('Excel.Application');
// Create the connection if we are adding to DataModel
// Now parse our gFileName
ConnPath := ExtractFileDir(gFileName); // Global Variable of the FileName
ConnFile := ExtractFileName(gFileName);
SheetName := 'RawData';
ConnRange := '$A:$H';
ConnCount := XLApp.ActiveWorkbook.Connections.Count;
ConnName := 'WorksheetConnection' + IntToStr(ConnCount) + '_' + SheetName + '!' + ConnRange;
ConnString := 'WORKSHEET;' + ConnPath + '[' + ConnFile + ']' + SheetName;
ConnCommand := SheetName + '!' + ConnRange;
gConnection := XLApp.ActiveWorkbook.Connections.Add2(ConnName, '', ConnString, ConnCommand, 7, True, False);
// Create the PivotCache
myPivotCache := XLApp.ActiveWorkbook.PivotCaches.Create(xlExternal, gConnection, 7);
// Create the PivotTable object;
StartCellRange := XLApp.ActiveWorkbook.ActiveSheet.Range['A5', 'A5'];
myPivotTable := myPivotCache.CreatePivotTable(StartCellRange, 'PivotTable1', True, 7);
// I can now see my Pivot Object in Excel
// Now add Filter Fields. I have tried multiple variations, but cannot get anything to work
// fFilter1 := XLApp.ActiveWorkbook.ActiveSheet.PivotTables('PivotTable1').CubeFields('[Range].[Category]');
// fFilter1 := myPivotCache.PivotTable.CubeFields('[Range].[Category]');
// fFilter1 := myPivotTable.CubeFields('[Range].[Category]');
fFilter1.Orientation := xlPageField;
Any help or ideas greatly appreciated.