473,379 Members | 1,367 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,379 software developers and data experts.

Create Pivot Table using VBA (Access 2007)

I have produced an Excel (2007) worksheet, with which I want to create a Pivot Table. This would all be done from a module run on an Access 2007 database.

Please can anyone supply some simple code for this?

Many thanks for any help received.
Apr 21 '09 #1
32 23324
NeoPa
32,556 Expert Mod 16PB
I'm afraid not.

We are here to assist people to develop their own work, not to do the work for them. There's flexibility to this, but in a case such as this, where it could easily be a homework or project question, we would be very hesitant to provide anything.

Please see the Posting Guidelines for how you could redo this in such a way that we can help.
Apr 21 '09 #2
This is not homework, nor a project question.

I have come across various bits of code on the net and looked at output from a macro recording when creating a pivot table in escel (2007).

However, when transferring this to a vba module, I keep getting errors. In a vain attempt to see if there was a quick and simple resolution to this problem, I raised this post.

I have seen far simpler (I know, in my opinion) problems resolved in this forum, so it seemed right to ask here.
Apr 21 '09 #3
NeoPa
32,556 Expert Mod 16PB
I'm certainly not saying you can't ask for help. Nor that the problem is too complex.

Please reread the post, with specific reference to the linked Help section that tells how questions should be asked. Posting what you have, with an explanation of what's failing where, would be acceptable. There is nothing to stop me, or anyone else, providing better code at that stage if that seems appropriate.

None of us is looking to make it hard to ask questions (why would we be here for that?), but the link does explain what we expect in the way of asking questions, and alo why if you're interested to look that deeply.
Apr 21 '09 #4
The current code looks like this, where Datasheet is the worksheet containing the data, and CurrentSheet is a new sheet being created to hold the Pivot Table:
Expand|Select|Wrap|Line Numbers
  1. With AppExcel.ActiveWorkbook.PivotCaches
  2.     With .Add(SourceType:=xlDatabase, SourceData:=Datasheet.Range("A1:H" & LastRowNumber), Version:=xlPivotTableVersion12)
  3.         Set PTable = .CreatePivotTable(TableDestination:=CurrentSheet.Range("A6"), TableName:="AnalysisPivot", DefaultVersion:=xlPivotTableVersion12)
  4.     End With
  5. End With
I have tried various versions of the above including holding the data/table output ranges in named variables.

Currently, this code returns a "Run-time error '448':Named argument not found" error message.
Apr 21 '09 #5
NeoPa
32,556 Expert Mod 16PB
Now you're talking.

I will see if I can help some here, but I'm not experienced with Pivot Tables. Probably later though as I'm working just now.

BTW. Can you say which line of the code the error message came on? It'll be either #2 or #3 I would guess, but that can tie down where to look.
Apr 21 '09 #6
The error is on Line #2
Apr 21 '09 #7
FishVal
2,653 Expert 2GB
Frankly speaking, the code looks fine.
Maybe Excel doesn't like the range you make PivotCache from.
I've made some trials and found that CreatePivotTable method fails if first cell in the range is empty.
Apr 21 '09 #8
FishVal
2,653 Expert 2GB
@redman08
what value is stored in LastRowNumber variable at this point?
Apr 21 '09 #9
Stewart Ross
2,545 Expert Mod 2GB
Beware! The macro recorder produces code that runs fine inside an Excel workbook where the Application object is implied. In an Excel sheet you can refer to ActiveSheet, ActiveWorkbook and so on without specifying the application object explicitly. However, references to implied Excel application objects do not work when running code in an Access VBA module using Access to communicate with Excel as an automation server.

For instance, the macro recorder frequently produces code where the ActiveSheet object is implied, so you will find things like

Range("A1:A1").<Do Something>

which fail in Access VBA, as there is no implicit Application.SomeWorksheet object wrapping the code to link back to the specified Range object.

You will need to fully qualify implicit references to tie them to the appropriate Application object, as you are doing in the first part of the With on line 1, and ensure that all object variables you use (such as DataSheet and CurrentSheet) are explicitly set:

Expand|Select|Wrap|Line Numbers
  1. ...SourceData:=Datasheet.Range("A1:H" & LastRowNumber)...
  2. ...TableDestination:=CurrentSheet.Range("A6")...
You will also need to check that the xlDatabase and xlPivotTableVersion12 constants are available within your Access VBA code module - the debugger can help you here - as if they are not you will need to substitute their actual values for the symbolic ones listed (or supply equivalent constants of your own).

I would expect to see lines like this to set the value of Datasheet, for example:

Expand|Select|Wrap|Line Numbers
  1. Dim DataSheet as WorkSheet
  2. Set DataSheet = AppExcel.ActiveWorkBook.Sheets("DataSheet")
  3. ...
If you have not set Datasheet as a worksheet object you cannot treat it as such in line 2.

-Stewart
Apr 21 '09 #10
NeoPa
32,556 Expert Mod 16PB
Thanks for picking this up guys.

I hadn't realised it was an automation issue. I might have been able to help there, but as you caught that already Stewart, I suspect there's little more for me to do.

I will keep monitoring of course.
Apr 21 '09 #11
FishVal
2,653 Expert 2GB
@redman08
I'm not sure about Excel 2007, but in Excel 2003 PivotCaches.Add method has no "Version" argument, which is, BTW, what error message is about.
Apr 21 '09 #12
Just to put more meat on the bones regarding definitions (and to repeat the problem coding):

Expand|Select|Wrap|Line Numbers
  1. Dim CurrentSheet As Variant
  2. Dim Datasheet As Variant
  3. Dim LastRowNumber As Integer
  4.  
  5. Dim AppExcel As Object
  6. Set AppExcel = CreateObject("excel.application")
  7.  
  8. LastRowNumber = AppExcel.WorksheetFunction.CountA(CurrentSheet.Range("A1:A65536"))
  9.  
  10. Dim PTable As Variant
  11.  
  12. Set Datasheet = AppExcel.ActiveWorkbook.Sheets("Data")
  13. Set CurrentSheet = AppExcel.ActiveWorkbook.Worksheets.Add
  14.  
  15. With CurrentSheet
  16.     .Name = "Analysis"
  17. End With
  18.  
  19.  
  20. With AppExcel.ActiveWorkbook.PivotCaches
  21.     With .Add(SourceType:=xlDatabase, SourceData:=Datasheet.Range("A1:H" & LastRowNumber), Version:=xlPivotTableVersion12)
  22.         Set PTable = .CreatePivotTable(TableDestination:=CurrentSheet.Range("A6"), TableName:="AnalysisPivot", DefaultVersion:=xlPivotTableVersion12)
  23.     End With
  24. End With
Hope I've not missed anything out.
Apr 22 '09 #13
FishVal
2,653 Expert 2GB
MSDN article does not enlist at all Add method in PivotCaches object in Excel 2007 object model. It could be supported though for backward compatibility but certainly with two arguments as in Excel 2003. At the same time PivotCaches.Create method is being called with arguments you try to pass to "Add" method.

P.S. Looks like excel 2007 automatically adds Workbook object to Workbooks collection when Excel.Application object has been created, otherwise the code will fail much earlier. IMHO, it is weird and may depend on Excel application settings which could vary from installation to installation.

P.P.S. Actually, I don't have any idea why the code doesn't fail on this line
Expand|Select|Wrap|Line Numbers
  1. LastRowNumber = AppExcel.WorksheetFunction.CountA(CurrentSheet.Ran ge("A1:A65536"))
  2.  
since CurrentSheet variable is not initialized.
Apr 22 '09 #14
Fishval, "LastRowNumber is set to 18 when the error occurs.

When using ".Add", I get an error '448' - Named argument not found,;

When using ".Create", i get an error '5' - Invalid procedure call or agument.

How do I check if "xlPivotTableVersion12" is set up ok (apologies if too daft a question)
Apr 22 '09 #15
FishVal
2,653 Expert 2GB
  • I still have no idea how LastRowNumber gets ever value since the code is more than expected to fail when you try to invoke method of not initialized object variable CurrentSheet (see my previous post), unless it is initialized with the code you haven't posted.
  • Check in object browser (F2 button in VBA IDE) what method "Add" or "Create" PivotCaches class has and what are the arguments of this method.
  • What happen if you just remove "Version" argument from the problematic code line?
Apr 22 '09 #16
Removing 'Version' parameter only produces a '448' error.
Apr 22 '09 #17
FishVal
2,653 Expert 2GB
What with the rest from post #16 ?
Apr 22 '09 #18
Stewart Ross
2,545 Expert Mod 2GB
If you need to find the last row number of the active sheet, there is no need to use CountA to do so. Like Fish I can't see why you don't have a run-time error occurring on the CountA line as a result of the uninitialised CurrentSheet object reference.

To find the last row number of the active sheet you can use

Expand|Select|Wrap|Line Numbers
  1. LastRowNumber = AppExcel.ActiveSheet.Range("A1").SpecialCells(xlLastCell).Row
This uses the .Row property of the Range object to return the row reference of the range to the last active cell. There is also a .Column property which will return the column number (as an integer, not in A, B...ZZ form) should this be needed.

Stewart
Apr 22 '09 #19
NeoPa
32,556 Expert Mod 16PB
@redman08
Not at all.

From the VBA IDE (Alt-F11 from the main app window), use Ctrl-G to go to the Immediate Pane, and type :
Expand|Select|Wrap|Line Numbers
  1. ?xlPivotTableVersion12
If any value is displayed then you know that it is set. If it is not recognised you will see a blank line.
Apr 22 '09 #20
NeoPa
32,556 Expert Mod 16PB
.SpecialCells(xlLastCell) is really useful in Excel worksheets, but there are circumstances where it's unreliable (When rows or columns have been deleted since the last save for instance).

A technique I use to get the last Row or Column of a particular column or row (NB. Only works when you know which column or row to look in) is to go to the last position and skip back.

EG. If I know that column A has a unique identifier in it (or PK), then I use :
Expand|Select|Wrap|Line Numbers
  1. Dim lngLastRow As Long
  2.  
  3. lngLastRow = Range("A65536").End(xlUp).Row
If I know Row 1 has the titles in it I may use (for the Column) :
Expand|Select|Wrap|Line Numbers
  1. Dim intLastCol As Integer
  2.  
  3. intLastCol = Range("IV1").End(xlToLeft).Column
These techniques are the VBA equivalents of using Ctrl-Up & Ctrl-Left from the extreme edges of the worksheet.
Apr 22 '09 #21
Re. xlPivotTableVersion12 ...I've got a blank line.
Apr 22 '09 #22
NeoPa
32,556 Expert Mod 16PB
That makes sense. That is a value set up in Excel, and probably available only there.

You can get around this by defining a constant in your code.
Apr 22 '09 #23
FishVal
2,653 Expert 2GB
Sacramental question:
Do you have "Microsoft Excel xx.x Object Library" referenced?
Apr 22 '09 #24
Checked on Excel: xlPivotTableVersion12 is set to 3, so have replaced xlPivotTableVersion12 with a constant.

Still no go!

I don't have "Microsoft Excel xx.x Object Library" referenced.
Apr 22 '09 #25
FishVal
2,653 Expert 2GB
So, reference it or use numeric equivalent of excel constants.

Oh, sorry, I see you've already tried. Did you replace all constants?

P.S. Anyway, I strongly recommend you to reference excel library in Access project. It will add Excel constants to Access namespace and enable Intellisense to resolve excel object model.
Apr 22 '09 #26
NeoPa
32,556 Expert Mod 16PB
That's an Office 2007 constant I see.

I tested in Access 2003 with a database with an Excel reference and saw nothing. When I changed it to xlPivotTableVersion10 it worked fine for me, so a reference to Excel should make that constant available to you, as Fish so rightly says.
Apr 22 '09 #27
I've added Microsoft Excel 12.0 Object Library and Microsoft Office 12.0 Object Library into my References....and am still getting '448' errors on line 2.

The code currently looks like this:
Expand|Select|Wrap|Line Numbers
  1. With AppExcel.ActiveWorkbook.PivotCaches
  2.     With .Add(SourceType:=xlDatabase, SourceData:=Datasheet.Range("A1:H" & LastRowNumber), Version:=3)
  3.         Set PTable = .CreatePivotTable(TableDestination:=CurrentSheet.Range("A6"), TableName:="AnalysisPivot", DefaultVersion:=3)
  4.     End With
  5. End With
There's not much to look at on that line. The SourceData is being referenced ok (have tested in debug for that); the Version number is ok. The only thing is "xlDatabase" - where is that picked-up from?
Apr 23 '09 #28
FishVal
2,653 Expert 2GB
I'd like to draw your attention back to post #14 and #16.
Could you check in object browser (button F2 in VBA IDE) what method PivotCaches class has "Add" or "Create" and what are arguments for the existing method?
Apr 23 '09 #29
Eureka!

It is Create, not Add, and the remaining parameters are as they are now.

Has run...now only the remaining bits...formatting...usage., etc.


Many thanks to all contributors.
Apr 23 '09 #30
FishVal
2,653 Expert 2GB
You are welcome.

Best regards,
Fish.
Apr 23 '09 #31
NeoPa
32,556 Expert Mod 16PB
Don't you just love those Eureka moments ;)

Very pleased to hear that's resolved Redman.
Apr 23 '09 #32
@redman08
This topic saved my life.
Thanks :PPP
Dec 28 '11 #33

Sign in to post your reply or Sign up for a free account.

Similar topics

2
by: Rob | last post by:
I'm just getting around to using pivot tables and charts. I find the Pivot table interface to be INCREDIBLY frustrating. When I view a table in Design view, then choose Pivot table view, I get...
4
by: Ajay | last post by:
Hello all, I used to display reports in Excel earlier on my website. Now the client has requested that he would like see reports in Pivot table on the web . The backend is Sql2000. Can you please...
1
by: peter | last post by:
Dear all, I have an existing query called 'A', but I want it to view in Pivot Table. What I do is : - Double click the query and choose Pivot Table view. - I make some changes by adding some...
9
by: PeteCresswell | last post by:
I've got something called "Reference Rates". The idea is that on a given day, we have various rates of return for various entities. e.g. Libor 3-month return, Libor 6-month return, US Treasury...
2
by: LittlePhil via AccessMonster.com | last post by:
Someone please help before i start to cry. I'm trying to export from Access to Excel, then create a new excel sheet with a pivot table to display the data held in columns A:P. I get the error...
18
by: smckibbe01 | last post by:
I have Pivot Table query in MS Access that I would like to run in SQL Server 2005. Can anyone help me to convert the syntax over to SQL Server. The following is the query in MS Access: ...
0
by: Sport Girl | last post by:
Hello everybody, please can anybody help me: How to make in a Pivot Table designed in Access 2007 a link from each field in the Pivot table to the corresponding row in the table in the database....
1
by: mld01s | last post by:
I really need help!!! I dont know if its possible to share pivot tables, or see pivot tables in other machines that the one where the tables were created. This is what happens: I created a...
0
by: Clare CAVS | last post by:
I have a table with a lookup column referring to another table . tblRooms has two fields, (Autonumber), and . The column I want to display is the RoomName column. If I have Bound Column = 1,...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.