Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Create Pivot table from two sheets

Status
Not open for further replies.

OMG_VBA_IS_GREAT

Technical User
Dec 1, 2017
16
US
Hi All,

I am struggling to get the following code to work. I want to create a pivot table using from two spreadsheets that have same column headers. Unfortunately, the macro fails. Any help or advise would be greatly appreciated.

Sub CreatePivot()

Dim i As Long
Dim arSQL() As String
Dim objPivotCache As PivotCache
Dim objRS As Object
Dim wbkNew As Workbook
Dim wks As Worksheet

With ActiveWorkbook
ReDim arSQL(1 To 2)
For Each wks In .Worksheets
i = i + 1
arSQL(i) = "SELECT * FROM [" & wks.Name & "!" & "A1:U10000]"
Next wks
Set wks = Nothing
Set objRS = CreateObject("ADODB.Recordset")

objRS.Open Join$(arSQL, " UNION ALL "), Join$(Array("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=", _
.FullName, ";Extended Properties=""Excel 8.0;"""), vbNullString)
End With

Set wbkNew = Workbooks.Add(Template:=xlWBATWorksheet)

With wbkNew
Set objPivotCache = .PivotCaches.Add(xlExternal)
Set objPivotCache.Recordset = objRS
Set objRS = Nothing

With .Worksheets("Pivot")
objPivotCache.CreatePivotTable TableDestination:=.Range("A3")
Set objPivotCache = Nothing
End With
End With
Set wbkNew = Nothing
End Sub
 
Hi,

I would used MS Query on a new sheet via Data > Get External Day > From Other Sources> From Microsoft Query > Excel Files*... and drill down to your workbook.

Here you can do a UNION ALL with your two or more tables. The results will be returned to the new sheet with data from all the tables, which can be the source for your PT.

You only need ADD the query table to your sheet ONE TIME. The query can be Refreshed as often as needed prior to refreshing the PT.

I never had success running a PT from multiple sources.

Skip,
[sub]
[glasses]Just traded in my OLD subtlety...
for a NUance![tongue][/sub]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top