VBA AddDataField CubeFields - Error 1004 - vba

I'm stumped...been building a PowerPivot sales report over the past few months and teaching myself VBA and DAX along the way. My report has several pre-configured views that can be chosen by VBA buttons, which work completely fine until you close the workbook and re-open it. Every time the workbook is opened for the first time - the VBA code errors out on the first AddDataField CubeFields line of code. It's as if excel does not pre-calculate the measure I am trying to add.
If I manually remove/add a value in the pivot table and then run the VBA code, it runs flawlessly. If I open PowerPivot manage data window and then close it, the VBA code runs perfectly fine. Something about manually changing values in the pivot table or simply opening the PowerPivot data tab, prompts Excel to pre-calculate all measures. Here is the exact line of code that gets hung up every time:
Worksheets("Dealer Install Sales").PivotTables("PivotTable1").AddDataField Worksheets("Dealer Install Sales").PivotTables( _
"PivotTable1").CubeFields("[Measures].[Sum of INVOICE_QTY]"), _
"PIECES"
How do I force excel to automatically calculate all measures upon opening the workbook?

I think what might be going on is the behaviour described in this joy-of-data blog post.
To paraphrase, a measure used in a pivot table which was created outside it, is "forgotten" in certain circumstances. A solution is to create a new measure within the pivot table field list (right click in field list and add measure), which simply references the original measure, e.g. =[measure name].
In your code, refer to the new name of measure, and when you do this, the data model should be stimulated into returning the value of the original measure, instead of falling over.

Related

Web Scrape Daily Treasury Rates

I have tried to write some VBA that scrapes a table from the URL below. I would like to create a macro that pulls in the data on a daily basis. Any help is much appreciated. Thank you
https://home.treasury.gov/resource-center/data-chart-center/interest-rates/TextView?type=daily_treasury_yield_curve&field_tdr_date_value_month=202212
I am having problems understanding HTML and the elements function.
I know you want to scrape that table on the treasury page, but it just has daily values of rates for each maturity duration (2yr, 5yr, etc.). These same rates are published every day in their XML feed.
The XML feed is meant to be consumed and parsed by computer code, while the HTML on that page is NOT meant to be parsed by "screen-scrapers".
If your macro pulled in the data from their XML feed every day instead, and you kept a table/log/whatever of each day's rates, after two weeks, you'd have the exact same data as the treasury HTML table, but NOT have all the headaches of trying to parse HTML and always worrying about your code breaking if their HTML layout changes.
Would this later approach work for you?
Update: Eric Salazar's answer reminded me of something. I don't know if you're using Excel VBA, or some other Office app, but if you ARE using Excel, you can use the "'Data Menu'->Get Data->From Other Sources->From Web" feature to import that treasury table into an Excel table. Simply copy the URL of that page, paste it into the URL field of the first dialog that pops up (keep type as "Basic"), click OK, click "Table 0" under Display Options of the next ("Navigator") dialog, and lastly click "Load". By default it will create a table in the current worksheet at the currently selected cell. It will contain all the columns of what's on the treasury page and a few more columns that will be filled with "N/A" (not sure where Excel is getting the N/A field names from). You can get rid of those fields by going into the Power Query Designer before importing the data (instead of clicking "Load" in the previous "Navigator" dialog, click "Transform Data" instead. This will open up the "Power Query Editor" and you'll see a table editor in the main window. Select the column headers you don't want to end up in the table and hit the "Del" key (or right-click and choose "Remove Columns"). The selected columns will now be gone. Now click "Close and Load" in the upper-left corner of the Power Query Editor window.
And like magic, Excel will create a new table on your current worksheet with the data contained on that treasury page. You can then access the table with regular VBA code to refresh and read the values.

Dictionary vs pivot Table and some office issues

In company when I currently work we have big issue with MS excel stability, hence my question below.
Recently I just learned about excel Dictonary code.
I know pivot tables and how they work.
sadly the issue is not with pivot themselves but with excel. (IT dept. is working on the issue for 3 weeks now, and we dont know when / if they gonna fix it)
Hence my big ask for thi community:
I would need a userform working with the dictonary.
What I would need is to create a code that could work as pivot table but using dictonaries (since theoreticaly they are faster and are outside of VBA / excel basic in-build option)
so?
Can some1 help in creating such code?
Is this the right option?
I would like to see a userform where I can choose my Table(ctrl+T) headers to choose by which header i want to sum values up, and ofc I would have to be able to choose a column by which the dictonary summing is working on.
Thank you both for answering.
Lets start then.
I watched ExcelMacroMastery videos regarding dictionaries,
In this example, he used them to make a basic sum exactly like the basic functionality of Pivot table.
So since that's the basic use where I work I wish to have a dictionary macro from which I can choose the column by which I get unique values and 2nd column with a sum from the second provided column from a table.
the issue is: if I show any file or any example this could result in macro working for this specific case, and I would like it to be able to choose by Table's (CTRL+T) headers for the unique values and to use some way(like a dropdown menu) to choose the column by which the sum can happen.
This instability is due to 32 bit office suite 365 working n 64 bi PCs/ laptops and recent company update made it even worse, now there is an issue with even basic save file option.
Not to mention excel crashing for no apparent reason.
So to sum up,
I need dictionaries to kinda step up and replace basic summarizing functionality of an pivot table.
or to replace this non pivot way:
use unique function to determine unique values from specified column (non-table object sadly)
Use sumif or sumoifs function to summarize the specified amount/value for that unique list.
//EDIT:
I kinda found what I was looking for thus the edit.
Im showing the link to the file I wish to change a bit:
https://app.monstercampaigns.com/c/s0iavndiopijkrar8ghp/
to this file I wish to add a user form by which the headers of the report will be chosen from source data, and by which the sum will occur.

Excel 2010 Macro Pivot Label Filter

I am having an issue running a label filter on a column (classic view) within my pivot table. I am trying to weed out the items in the data that are less than 180 days old. I can't adjust the data because it is used to feed multiple worksheets and I don't wish to copy the data and manipulate it for just this worksheet. Below is the line that I am running.
ActiveSheet.PivotTables("PivotTable5").PivotFields("Ageing").PivotFilters.Add _
Type:=xlCaptionIsBetween, Value1:="180", Value2:="9999"
This is a "between" filter. I have tried greater than and greater than or equal to but the same result occurs. After this line is run, I can click into the pivot table soft/filter down arrow and see that the filter is there as a between and even the days are inputted but the data does not reflect this. If I hit "OK" on the filter it then applies itself but I do not wish to have to do this manually.
Yes, "PivotTable5" is the pivot table in question. Can anyone help me automate this process?

Unable to move / delete rows in shared workbook - Not enough resources

this one's a bit of a painful one so thank you for your help and patience with me.
We have an Excel spreadsheet that we use as a master file for our website products. As such there are quite a few sheets and quite a few products on each running along side some macros to provide some extra functionality (turning entered data into HTML for product page, etc).
My issue is that one of our most used spreadsheets has become a trouble in that it has some phantom formatting all the way down to the millionth-and-something row and all the way across, causing the last cell to be the very last cell possible.
The issue that has finally popped up as a result is that we can no longer move rows in, out or around the sheet (a required functionality) as it results in an 'out of resources error'.
I've tried:
Highlight all rows below used range to right-click> delete - Results in runtime error (from macro)
Highlighting large chunks of rows and using Clear All - Resulted in the 38MB file bloating to 380MB
Deleting a chunk of rows at a time - Maxed out at 1,000 before it caused Excel to crash
Moving to new spreadsheet - Broke all our macros (which I did not write and am not proficient enough to fix on a new sheet)
Disabling macros and trying the above options, only marginally more efficient but still out of resources
I'm at my wits end on this one and, while we can continue with most day-to-day functions, we will soon be completely unable to use this particular sheet as we need it at all.
I'm wondering if there might be a way to run a VBA script to remove these rows, potentially one by one? I've tried running a short script that went something like rows[960,1000000].Delete (forgive my terrible VBA markup), but this also resulted in not enough resources errors.
I'm wondering if there's anything like:
row = 960;
while(row<=1048576){row.Delete};
Continuing, the runtime error debug points me to the below if statement within the macro:
If Target.Count > 1 Then Exit Sub
Where Target is the variable passed to the sub.
Which strikes me as very odd because my (limited) understanding of VBA and IF's in general simply recognizes that 'if my selection is larger than 1 (row?), do not run this code..
Thanks again in advance.
Use this method only if you don't have any links into or out of the sheet that will get broken. Also might have Sql connections that might get broken. Might need to disable macros. There are many possible problems with this approach. Use at your own risk.
Note the exact "Name" and "(Name)" of the sheet; Look in the VBA code window at the properties for the sheet. "Name" is the name displayed on the worksheet tab. "(Name)" is the code name visible only in the properties window.
Make a list of range names on the sheet.
Copy the data to a new sheet.
Copy any macros to the new sheet.
Delete the old sheet.
Rename the "Name" and "(Name)" of the new sheet the same as the old one.
Recreate range names.
A better method if you don't have too many formats:
Disable macros and set calculation to manual. This avoids recalculating while doing your delete operation.
Select entire sheet and clear formats.
Delete all rows below your data.
Redo your formatting. Select entire column (not just used area) to apply format if applicable.
It is important to remove formatting on the entire sheet from A1 to the end. Otherwise you'll get the bloat you mentioned. Just that step may solve your problem. If not then proceed with removing all the rows below the data. This should not cause file size bloat.

How can I display the MDX generated by Excel 2007 when using a pivot table?

Pretty much what the title says. Is it possible to show the MDX that is sent to OLAP source when using a pivot table in Excel 2007?
You can download the OLAP Pivot Table Extensions from the codeplex site( http://olappivottableextend.codeplex.com/)
Install it.
You can then right click and see the OLAP query.
Regards,
Ambarish
I was curious to see the MDX generated by a pivot table in Excel also. Apart from imputing MDX manually I couldn't see a way to see the MDX after a user has selected and filtered etc.. on the pivot table itself.
But I found a quick vba snippet here
PivotTable.MDX
All I did was ALT + F11 to bring up the VBA window
Insert a userform like so
Click inside the textbox inside the userform and change these two settings in the properties window
Multiline - True
Wordwrap - True
Paste in the code below
Sub CheckMDX()
Dim pvtTable As PivotTable
Set pvtTable = ActiveSheet.PivotTables(1)
UserForm.TextBox.Value = pvtTable.MDX
UserForm.Show
End Sub
Make sure your Pivot Table is the active sheet (i.e have the worksheet open on the pivot table clicked in a cell).
Press the run button and a userform should pop up like so where you can copy out the MDX text.
This was on Excel 365. Hope this helps.
If you have profiler you could set up an Analysis Services trace and catch it on the way, or do you need to see it without executing it?
While the OLAP Pivot Table Extensions are still available for Excel 2013, you can no longer right-click on the table and view the MDX. This is yet another example of MIcrosoft going out of their way to make life more difficult for end-users and developers. The ability to view MDX for the current PivotTable selections should be built into Excel. It's not because Microsoft's developers either were too careless to give such a critical thing priority or because the powers that be saw a potential for an add-on product. Regardless, it's an example of why they are often hated. Over the years I can't even count all the hours of life I've lost outside the normal workday because the incompetent or malevolent behavior of Microsoft's manager, developers... But what other toolset can do what Excel and SSAS do? It's not an easy thing to replace so we have to deal with their crippled tools.
There is a free web based pivot table tool called WebPivotTable which can connect to SSAS cube directly and display each MDX statement for teh current PivotTable selections. It has all functions as Excel but with more intuitive user interface. In MDX windows, you can even test your own MDX statement and get results displayed in table and charts.
Here is Demo and Documents.