Close Window
Free Ebook
Get Your Free Excel
Top 15 Excel Tutorials from
Instant Access!

Update Pivot Table Populated By Recordset - Adodb


If I use the procedure shown in this post (copy below, procedure name "createPivotTable") to create a recordset from a worksheet or a named range, and then use the recordset to create and then populate a pivot table, what will the correct procedure be to update the recordset and then to update the pivot table if:

1. values in the existing data source change,
2. if the number of records in the existing data source changes,
3. if the structure of the existing data source changes (add, take away columns/fields)
4. if I need to add a second or third worksheet or named range to the data source?

I tried the procedure below (name "refreshPivotTable") but it does not always work, specifically:

1. if I add an additional worksheet or a named range to the data source, then the update procedure fails (the procedure does not recognise the name of the new data range). I then need to save the file, close Excel, reopen the file and rerun the procedure, at which time the new data range is taken into consideration and the pivot table refreshes correctly,
2. changes to the structure of the data source do not show after the pivot table is refreshed, i.e. new fields do not show in the pivot table, or they do show but the values which belong to this field do not show in the pivot table.

Therefore, is there a better way to make the pivot table update as my source data changes? Am I doing this the wrong way?

Any tip will be greatly appreciated.


Sub createPivotTable()
With ActiveWorkbook
arSQL = "SELECT * FROM [03-11$]"
Set objRS = CreateObject("ADODB.Recordset")
objRS.Open arSQL, _
Join$(Array("Provider=Microsoft.jet.OLEDB.4.0; Data Source=", _
.FullName, ";Extended Properties=""Excel 8.0;"""), vbNullString)
End With
Set objPivotCache = .PivotCaches.Add(xlExternal)
Set objPivotCache.Recordset = objRS
Set objRS = Nothing
objPivotCache.CreatePivotTable TableDestination:=Sheet1.Range("A3")
Set objPivotCache = Nothing
End Sub

Sub refreshPivotTable()
With ActiveWorkbook
arSQL = "SELECT * FROM [03-11$] UNION ALL SELECT * FROM [04-11$]"
Set objRS = CreateObject("ADODB.Recordset")
objRS.Open arSQL, _
Join$(Array("Provider=Microsoft.jet.OLEDB.4.0; Data Source=", _
.FullName, ";Extended Properties=""Excel 8.0;"""), vbNullString)
End With
Set ThisWorkbook.PivotCaches(1).Recordset = objRS
Set objRS = Nothing
End Sub

Free Excel Courses

Similar Excel Tutorials

How to create dynamic charts that update automatically when new data is added to Excel. This method uses the table ...

How to get the nice formatting of a table without turning your data into an actual table. Formatting data as a tab ...

Convert a table back into a regular set of cells.  This removes any automated table features and I'll show you how ...

Filtering allows you to hide rows of data which you are not interested in so that you can easily look at the rows y ...

Helpful Excel Macros

- This macro will pull the values from a chart in excel and list those values on another spreadsheet. This will get the s

- Create a bar chart in Excel with this macro. You will be able to quickly and easily turn any range of numbers and data

- Import data from the web into Excel with this macro. This is a basic web query macro that will import data from any web

- This Excel macro sorts data that has headers in descending order. This means that data is sorted Z to A and 10 to 1 - o

- This macro adds a column chart to Excel. This is an easy to use macro that allows you to quickly chart and graph a rang

Similar Topics

Also, I cannot move the Pivot Table from the new Worksheet it is created in, to my existing Worksheet.

I am running Excel 2011 for Mac.

I have a Worksheet with a small amount of data, and when I click the Pivot Table button it automatically creates the Pivot Table in a new Worksheet. The Pivot Table data is fine, but I want it to display alongside the source data.
I've tried using the Move Pivot Table option and choosing to Create Pivot Table in Existing Worksheet and choosing a source cell alongside my current data, but nothing appears. Also, I checked in Edit menu and found that the Pivot Table appears to have not even been created/moved because there is no option to undo it.

Appreciate any help, let me know if you have any further questions.


I have a very simple pivot table that I am trying to use as a data source for a VLOOKUP request. Unfortunately, every time I do it I get the result #NA. I have tried recreating the results from the pivot table in the worksheet next to it, and am able to use VLOOKUP on them successfully, but as soon as I point the VLOOKUP array to the pivot table, I get the #NA result

Can VLOOKUP be used on pivot tables? If so, is there any special syntax I need to use?



I am copying charts to display the same information for different regions. When I work on the copied region, I find it a cumbersome task to go through each charts source data and change the cell references to the different region. Essentially I am doing a trending analysis for each region, with a region having its own sheet with 5 charts per sheet. What I have done is copy the original sheet and am updating the sheet for another regions source data by going to the source data. The source data is all in the same row/column format, but each regions source data has its own sheet. Is there a more automatic way to do this? Perhaps a way to update all 5 charts references at the same time.


Recently, I find that the Pivot Table toolbar does not show up when I activate it. I have reinstalled Excel but it still does not show up when I activate it in the Pivot Table. Can someone advise me on what settings I shoudl do to turn it on again ? Thanks.

In my pivot table I have a lot of cells without any data. The report looks like garbage with all the (BLANK) sohowing up in the report.

I've tried condtional formatting where if the cells = (BLANK) it woulf format them as white -did not work

I tried the pivot table options and clicking on the box "for empty cells show" and set it to 0 then empty but that did not work.

any Ideas???


Hi everyone,

I found an excellent macro this morning that allows the user to filter a pivot table based on the value found in a specific cell. This cell essentially acts as a search bar, allowing the user to type in what they are looking for rather than select it from a drop-down list.

The macro works perfectly for my purposes except in one regard: I can no longer perform a "show all" filter. If I leave the "search bar" cell blank, the pivot table shows nothing. I'm sure that there is an easy fix for this but I'm still learning the basics of how to write and use macros. How can I change the code so that when I leave the cell blank, the pivot table shows all? The search bar cell is D2.

Thanks for your time!

i want to retain the data and format, but get rid of the pivot capacity before sharing the spreadsheet. right now if a copy/paste special, i can get the data, but not the formats, any suggestions?


Im working with a large data spreadsheet that has Yes and No answers in different columns. There are blanks within the selection too.
I need to calculate only the Yes.
I have tried using the filters in the Pivot Table field list and they are not working.
So now i'm trying to add a COUNTIF formula in the Calculated Fields section.
The formula I'm using is =Countif('Time limit extension'="yes") and i get the answer "too few."
What should I be using in the formula to get the calculated field to work? I have search the whole forum and I haven't found an answer that can help me.

Please HELP!!!

Hello everybody,

We all know we can change the source of a link of the workbook by clicking Edit>Links>Source>change source but that will change the source of all workbook formulas which are linked to a certain file, what about if i need to change the source of a single sheet? is this possible?

I appreciate your support.Thank you !

Dear Sir,

If any one could give me a solution for this its will be a great help for me.

I am working in a bank and on every day we receive Month to date data of Loans and advances made by every branch with Region wise total and manager wise total. With Sum of loan and count of loan. In our MIS format the in A coulum branches are sorted and listed in a sequence with sub total Region. I have data where if if do the pivot and change the data the out put should be displayed accordingly in the MIS format. Can any one help me how can we do this or is there any other office addins/softwares are available if so the data is changed on a daily basis and if we do the pivot it will automatically copy the data to the MIS format.


Hi there,

I have a spreadsheet with some cells setup with a drop-down list containing
Y, N or N/A

This is being used on a TabletPC but if I make a mistake or need to change
back to a blank field I have to invoke the soft keyboard, activate the cell
and hit backspace then close the soft keyboard - quite a long-winded
procedure just to change an incorrect choice!

What I would like to do is add a blank to the list so if I have to revert
back to a blank I can just use the stylus to choose a blank from the chooser

How do I add the option of inputting a blank from the Data Validation List
bearing in mind I am using the Data Validation Source box for entering my
choices directly and not specifying a range of cells?

I have tried adding "" and even a space to no avail.

Although not a betting man I would wager there is a simple 'fix' for this
but things are only simple if you know how in the first instance! ;^)

Thanks & regards,

I would like to copy a small table from Word into one cell in an Excel
worksheet. The first column of the table is a list of numbers. I tried
converting the table into text with manual line breaks and tab stops to
divide columns and rows, but that didn't solve my problem.

Excel pastes the data into several rows. When I try to merge them, I
get a warning that the selection contains multiple data values, and
merging into one cell keeps the upper-left most data only.

What I tried that didn't work:
* Formatting the Excel cells as text before pasting the data.
* The various options for "Paste Special." The closest I got was
inserting the table as a Document Object, which could be a workaround,
I guess.
What I am saving for when all else fails:
* The obvious solution of copying row by row into one Excel cell.

The data in the table is information about my dad's medications. I
would like to have reference charts of how to identify the strength of
each tablet by its color and markings. I got the info from the
manufacturers' websites and entered it into tables in Word, which I
would like to copy into a more comprehensive file I am creating in
Excel. The first column of each table is the strength of the tablet,
entered as 1 mg., 2 mg., etc. The subsequent columns describe the
shape, color, and markings. There are 3 tables, each with about 4-5

Is there a way to copy each one - whether as a table or as text - into
a single Excel cell without losing data?

Many thanks.

I am using XL2007 and have a macro that refreshes microsoft query connections. The issue is the refreshes only happen if you step through the macro using the debugger. When you run the macro normally, everything else functions properly, but the data is not refreshed.

Any help is appreciated. Here is an excerpt of the code:

Workbooks.Open Filename:="C:\Profile.xls"
Range("F3").Value = SNR

ActiveWorkbook.Connections("Query from C_Profile").Refresh
ActiveWorkbook.Connections("Query from C_Profile1").Refresh

Using VBA, I am trying to retrieve the contents of the Source of a web page (the same as would appear if you right-clicked on the page and chose "View Source") into a variable so I can work on it in VBA (using InStr, etc.).

The problem is I can use code such as
strHTMLText = ie.Document.body.innerText
strHTMLText = ie.Document.body.outerText
to retrieve the code, but in either case only part, not all, of the source code is captured. I need ALL the code. Is there some kind of code such as ie.Document.body.allText or similar that would perform this function?

Much obliged!

I have workbook in which I want to save a specific worksheet to a new file with only the values saved - all data in this worksheet are references to cells on another worksheet, which is using VLOOKUP to pull data from a database.

Found the following code and it gets me close, but it copies the cell references, not the values. It also allows me to specify the file name from a cell reference.

I want the new workbook file to simply be saved, not opened, and a message box to display stating where the file was saved (will always be in the same location on the LAN).

What modifications do I make to this to get this to work per above requirements?

Sub CopyMe()
Dim SaveMeAs As String
SaveMeAs = Sheets("Sheet1").Range("B2").Text
ActiveWorkbook.SaveAs Filename:="C:\My Documents\" & SaveMeAs
End Sub

I just worked with a data set where I needed to create a unique key based on existing information where no unique key was set up as a field. I accomplished it by concatenating (using the & [concatenation] operator) several fields based on what I hypothesized and observed about their content.

I'm thinking there has to be a more automated way to discover the best unique key of existing fields and their data. I thought I'd post this as a challenge because I don't know the "right" (or better) answer.

Anyone have any ideas?

I am looking for the code to select the visible data after applying a data filter. Actually I know how to select the data after applying the data filter but the issue is I am not able to exclude the header row and give the target range as used (non-blank) rows only!!

I am using below code to Select the Visible rows in the target range:



Problems in this code a

1) after applying the filter, while selecting the data it is selecting all the rows in given range till last row on the workbook. I need this to select the the data only till the last used row in the given range.

2) It is not possible to provide the address of the first row after we apply the filter since the first row address may change depending on the values in the table.

E.g. 1st time when I am running the macro the first row in the visible filtered data is starting at Cell address A4 and next time when I will run the macro it may be A6

3) The Code is also selecting the 1st row which is a header row. How can we exclude it from selection.

Some one please revert with the solution.
Thanks in advance.

Hey there,

I have been tasked with introducing userforms into an excel sheet and tbh I'm quite amazed that excel has this capability of adding userforms to excel sheets.

Anyway, I have 2 columns of data in an excel sheet and I wish to add this to a userform so that the userform displays the 2 columns beside each other with headings, like a table. The user should then be able to select a particular row and insert it into the specified cell.

I would also like the user to select a row on the table and then be able to bring up another table depending on the row selected...basically so that the user can draw deeper into the information that they require.

I have an example excel sheet where I have 2 sheets. One sheet is the user entry sheet called User Entry Screen. the next sheet is the tables sheet where my tables are held. Once the user selects the cell shown in the example sheet, it should then bring up the user form. the user then, depending on which item clicked, then gets shown the next window with a table and info on it. then user should then be able to select an item and the cells on the user entry screen would then get populated.

Personally I think this is a really tricky challenge and any help with doing this would be extremely appreciated.

I'll post up further comments as I am trying to work my way through it!




I have the following code to put data from a VBA userform into Excel

Dim Sh As Worksheet
Dim Rng As Range
Set Sh = ActiveSheet
Set Rng = Sh.Range("A65536").End(xlUp).Offset(1, 0)
With Rng
.Cells(1, 1) = Surname.Text
.Cells(1, 2) = forename.Text
.Cells(1, 3) = datein.Text
.Cells(1, 4) = origin.Text
.Cells(1, 5) = Addressee.Value
.Cells(1, 6) = usual.Value
.Cells(1, 7) = dateto.Text
.Cells(1, 8) = permission.Value
.Cells(1, 9) = dateseen.Text
.Cells(1, 10) = requestview.Value
.Cells(1, 11) = Invoice.Value
.Cells(1, 12) = notes.Text
.Cells(1, 13) = datecompleted.Text
.Cells(1, 14) = holdsend.Value
.Cells(1, 15) = fee.Text
.Cells(1, 16) = notes2.Text
.Cells(1, 17) = dateseen.Text
.Cells(1, 18) = invoicesent.Text
.Cells(1, 19) = Paid.Text
.Cells(1, 20) = Complete.Value

End With

What I want to do next is click on the surname on the speadsheet and call up the userform with the fields complete for that person. I would also like to be able to edit/update the form and update the information on the speadsheet accordingly.

Any help would be greatly appreciated!

Many thanks!

Is it possible to apply a filter to multiple sheets within the same Excel workbook, using the same filter criteria?

For example, suppose you have tables of data on 3 different tabs, all having the same headings. Suppose one of the headings is "gender". If you apply a filter to the table on Sheet 1, to only show the rows containing the word "female", is it possible to have the tables on Sheets 2 and 3 automatically update to only show the "female" rows? Or would you have to manually update the filter criteria in Sheets 2 and 3?

I hope this makes sense. Thank you in advance for any help.

I have a pivot chart with a bunch of data series, and every time we
include/exclude one of the series to see how the chart changes, all the
colors change and we have to spend time re-identifying which series is
which, using the legend to check the colors.

Is there a way to "lock" the colors, so that the bars stay the same colors
regardless of whether other bars are included/excluded?


Hi All,

I have the below code which deletes all items from a listbox and my excel sheet which is the source for populating that listbox. I am using a option button style for my listbox and the selection style as single .i.e. you can select only one item at one go in the lisbox. I want my macro to delete the selected item from my worksheet .i.e. it's entire row so that it doesn't reflect in my lisbox any more. Below is my code :


Private Sub CommandButton2_Click()
 Dim I As Long
 With ListBox1
 For I = .ListCount - 1 To 0 Step -1
 If .Selected(I) Then
 .RemoveItem I
 Sheets("URL List").Rows(I + 2).EntireRow.Delete
 End If
 Next I
End With
End Sub

Thanks a lot for your help in advance.

Hi all,

I have written some code that when a button is selected will Refresh a Data Query Table and all of it's information. However, I seem to be getting issues, can some one point me in the right direction with the code?


.Sheets("Sheet 1").ListObject.QueryTable.Refresh BackgroundQuery:=False

When I recorded myslef doing this process it looked like this:


Sheets("Sheet 1").Select
Selection.ListObject.QueryTable.Refresh BackgroundQuery:=False

Many thanks!


This is a very basic question, but i have been struggling for hours, so I must ask.

I I trying to simply fill a combobox on a userform from a named range on a sheet, I want to populate the combobox as soon as the userform starts. (I launch the userform from a button on the sheet) Where must I place the code? and will this code work?

Sub Button1_Click()
Set UserForm1.combobox1.List = Sheets("Sheet1").Range("MyRange")
End Sub

I am very new to vba, so please excuse my ignorance,
any help would be greatly appreciated


Is there a way to use the new conditional formats (data bars, icon sets, etc) in PowerPoint? Basically, I'd like to create a table that shows icons based on data, like in Excel? I know I could paste a pre-made Excel table as a picture, but I'd like to avoid that if possible.


Related pages

how to compute number of hours in excelsumif function multiple criteriapercent change formula excelhack vba passwordleague schedule generator freeexcel minus one monthexcel count highlighted cellsunzip xlsx filesort by last name excelbancfirstonline comdata analysis toolpak mac excel 2011div error in excelconvert letter to binaryhow to copy and paste excel sheets exactlydynamic range vbaleague schedule generatorexcel bridge chartvlookup to find duplicatesvba error 13excel combine multiple rows into one cellpowerpivot iconsearch duplicates in excelnested if statement in excel 2010excel bell curve graphexcel vba jsonhow to create an invoice on exceltally marks in excelhow to convert kbps to mbpsexcel spreadsheet for warehouse inventoryimacros tutorialssoftball stat keepervba checkboxcannot merge cellshow to remove compile error in hidden modulecreatinine clearance formulasexcel macro delete columnexcel countif colorsendkeys vbacrockoft gaulttrim function in vbavba excel countifexcel interpolatemacro loop excelcalculating hours worked in excelclustered column chart excelexcel formula if cell contains valuehow to unhide multiple tabs in excelhow to calculate minutes for payrollcolon in excel formulahow to recover unsaved file in excelexcel disable compatibility checkerconcatenate in excel 2007how to calculate ageing in excel by datesvlookup date rangeexcel stacked barshort key for merge and center in excelexcel formula for percent increaseexcel matrix multiplicationdata entry form in excel 2007activeworkbookextrapolation formula excelbradford calculatorvba excel loophow to use comma separator in excelmicro security in excel 2007hyperlink in outlook signatureunhide all cellsms excel watermarkexcel delete blank pagesvba excel file openhow to calculate percentage in excel sheetmax formula in excelhow to remove all macros from excel filecrack excel vba passwordhow to calculate total interest paid in excelcreating userforms in excelexcel hyperlink to another sheetdaily expenses record excelembed forms.combobox.1how to enable macros in excel 2007 permanentlyexcel save as xmlqueueing theory formulaswhat is intercompany reconciliation