473,498 Members | 1,700 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Help looping thru multiple workbooks to merge data into Masterr worksheet

1 New Member
I am having issues with the data being placed in the master workbook which contains multiple worksheets that have data tables In one case if SHNames = "Proj Sum" then it is placed outside of the table and not recognized by Pivot table, the other if the shName = "ResPlan_Data", there are multiple rows of blank lines in the Table and no data is updated.

Please help to correct the code accordingly. Sample file available on request , it too large to post here.

Expand|Select|Wrap|Line Numbers
  1.  
  2. '************** Code Start **************
  3. 'This code was originally written by Terry Kreft.
  4. 'It is not to be altered or distributed,
  5. 'except as part of an application.
  6. 'You are free to use it in any application,
  7. 'provided the copyright notice is left unchanged.
  8. '
  9. 'Code courtesy of
  10. 'Terry Kreft
  11. '*****************************************
  12. Private Type BROWSEINFO
  13.   hOwner As Long
  14.   pidlRoot As Long
  15.   pszDisplayName As String
  16.   lpszTitle As String
  17.   ulFlags As Long
  18.   lpfn As Long
  19.   lParam As Long
  20.   iImage As Long
  21. End Type
  22.  
  23. Private Declare Function SHGetPathFromIDList Lib "shell32.dll" Alias _
  24.             "SHGetPathFromIDListA" (ByVal pidl As Long, _
  25.             ByVal pszPath As String) As Long
  26.  
  27. Private Declare Function SHBrowseForFolder Lib "shell32.dll" Alias _
  28.             "SHBrowseForFolderA" (lpBrowseInfo As BROWSEINFO) _
  29.             As Long
  30.  
  31. Private Const BIF_RETURNONLYFSDIRS = &H1
  32. Public Function BrowseFolder(szDialogTitle As String) As String
  33.   Dim X As Long, bi As BROWSEINFO, dwIList As Long
  34.   Dim szPath As String, wPos As Integer
  35.  
  36.     With bi
  37.         .hOwner = hWndAccessApp
  38.         .lpszTitle = szDialogTitle
  39.         .ulFlags = BIF_RETURNONLYFSDIRS
  40.     End With
  41.  
  42.     dwIList = SHBrowseForFolder(bi)
  43.     szPath = Space$(512)
  44.     X = SHGetPathFromIDList(ByVal dwIList, ByVal szPath)
  45.  
  46.     If X Then
  47.         wPos = InStr(szPath, Chr(0))
  48.         BrowseFolder = Left$(szPath, wPos - 1)
  49.     Else
  50.         BrowseFolder = vbNullString
  51.     End If
  52. End Function
Expand|Select|Wrap|Line Numbers
  1. '**************************************
  2. 'Merges all workbooks into Master Template workbook
  3. '*************************************
  4. Public Function MergeMultipleSheets()
  5.     Dim MyPath As String, FilesInPath As String
  6.     Dim MyFiles() As String
  7.     Dim SourceRcount As Long, FNum As Long
  8.     Dim myBook As Workbook, wbMaster As Workbook
  9.     Dim BaseWks As Worksheet, ws As Worksheet
  10.     Dim sourceRange As Range, destrange As Range
  11.     Dim rnum As Long, CalcMode As Long
  12.     Dim rng As Range, SearchValue As String
  13.     Dim FilterField As Integer, RangeAddress As String
  14.     Dim ShName As Variant, ShNames As Variant, RwCount As Long
  15.     Dim nFilter As String
  16.     Dim currentrow As Long
  17.     Dim LastRow As Long
  18.  
  19.     MyPath = ThisWorkbook.Sheets("Data Input").Range("B1")
  20.   '  ShNames = Array("ProjSum", "FinSum", "CommSum", "InvPlan", "ResPlan")
  21.     ShNames = Array("ProjSum", "ResPlan_Data")
  22.  
  23.     Set wbMaster = ActiveWorkbook
  24.     '**********************************
  25.     'Merge data into existing worksheets in this workbook
  26.     '**********************************
  27.  
  28.     ' Add a slash after MyPath if needed.
  29.     If Right(MyPath, 1) <> "\" Then
  30.         MyPath = MyPath & "\"
  31.     End If
  32.  
  33.     ' If there are no Excel files in the folder, exit.
  34.     'FilesInPath = Dir(MyPath & "week*.xl*")
  35.  
  36.     nFilter = ThisWorkbook.Sheets("Data Input").Range("B2")
  37.     If nFilter = "" Or FilesInPath = "" Then
  38.         FilesInPath = Dir(MyPath & "*.xl*")
  39.     End If
  40.  
  41.  
  42.     ' Fill the myFiles array with the list of Excel files in the
  43.     ' folder.
  44.     FNum = 0
  45.     Do While FilesInPath <> ""
  46.         FNum = FNum + 1
  47.         ReDim Preserve MyFiles(1 To FNum)
  48.         MyFiles(FNum) = FilesInPath
  49.         FilesInPath = Dir()
  50.     Loop
  51.  
  52.     ' Change application properties.
  53.     With Application
  54.         CalcMode = .Calculation
  55.         .Calculation = xlCalculationManual
  56.         .ScreenUpdating = False
  57.         .EnableEvents = False
  58.     End With
  59.  
  60.     ' Clear data from summary worksheets
  61.     For Each ShName In ShNames
  62.         Set rng = Nothing
  63.         On Error Resume Next
  64.         Set rng = wbMaster.Worksheets(ShName).UsedRange
  65.         On Error GoTo 0
  66.         If Not rng Is Nothing Then
  67.             Set rng = rng.Offset(1, 0)        'Don't delete header labels in the first row
  68.             rng.EntireRow.Delete
  69.         End If
  70.     Next
  71.  
  72.     rnum = 1
  73.  
  74.     ' Loop through all files in the myFiles array.
  75.     If FNum > 0 Then
  76.         For FNum = LBound(MyFiles) To UBound(MyFiles)
  77.             Set myBook = Nothing
  78.             On Error Resume Next
  79.             Set myBook = Workbooks.Open(MyPath & MyFiles(FNum), UpdateLinks:=0)
  80.  
  81.      '*************************************
  82.      'Removes unused Named Ranges from Name Manager from the Various JC files to prevent error dialogs.
  83.      '**************************************
  84.                For Each nName In Names
  85.                     If InStr(1, nName.RefersTo, "#REF!") > 0 Then
  86.                         nName.Delete
  87.                     End If
  88.                     If InStr(1, nName.RefersTo, "https://") > 0 Then
  89.                         nName.Delete
  90.                     End If
  91.                 Next nName
  92.             On Error GoTo 0
  93.  
  94.             If Not myBook Is Nothing Then
  95.  
  96.                 For Each ShName In ShNames
  97.                     Set ws = Nothing
  98.                     On Error Resume Next
  99.                     Set ws = myBook.Worksheets(ShName)
  100.                     On Error GoTo 0
  101.      '*************************************
  102.      'Calls function to update ResPlan in active workbook
  103.      'Executes Updating of the ResPlan data to proper format for extraction of data in correct format
  104.     '***************************************
  105.                     If ShName = "ResPlan_Data" Then
  106.                         Call UnpivotResPlan
  107.                         myBook.Save
  108.                      End If
  109.                   '**************************************
  110.                   'Updates template data per shName
  111.                   '**************************************    
  112.                     If Not ws Is Nothing Then
  113.                         Set BaseWks = wbMaster.Worksheets(ShName)
  114.                         Set sourceRange = ws.UsedRange
  115.                         Set rng = sourceRange.Offset(1, 0).Resize(sourceRange.Rows.Count - 1, sourceRange.Columns.Count)    'Exclude header labels
  116.  
  117.                         RwCount = rng.Rows.Count
  118.                         rnum = BaseWks.Cells(BaseWks.Rows.Count, 1).End(xlUp).Row + 1
  119.  
  120.                         BaseWks.Cells(rnum, "A").Resize(RwCount).Value _
  121.                               = myBook.Name
  122.                         BaseWks.Cells(rnum, "B").Resize(RwCount, rng.Columns.Count).Value = rng.Value
  123.                     End If
  124.                 Next
  125.                     ' Close the workbook without saving.
  126.                     myBook.Close savechanges:=True
  127.             End If
  128.         ' Open the next workbook.
  129.         Next FNum
  130.  
  131.     Call UnpivotSalaryDetail
  132.         ' Set the column width in the new workbook.
  133.         BaseWks.Columns.AutoFit
  134.     End If
  135.  
  136.     ActiveWorkbook.Model.Refresh
  137.         If Worksheets("Resplan_Data").Visible = True Then
  138.             Worksheets("Resplan_Data").Visible = False
  139.         End If
  140.     Call Reset
  141.         MsgBox "Update Completed!"
  142.     ' Restore the application properties.
  143.     With Application
  144.         .ScreenUpdating = True
  145.         .EnableEvents = True
  146.         .Calculation = CalcMode
  147.     End With
  148. End Function
  149.  
Expand|Select|Wrap|Line Numbers
  1. Sub UnpivotResPlan()
  2.     Unpivot Worksheets("ResPlan")
  3.  
  4. End Sub
Expand|Select|Wrap|Line Numbers
  1. Sub UnpivotSalaryDetail()
  2.     Dim wsDest As Worksheet
  3.  
  4.     Unpivot Worksheets("SalaryDetail")
  5. End Sub
Expand|Select|Wrap|Line Numbers
  1. Sub Unpivot(wsSource As Worksheet)
  2.     Dim i As Long, ii As Long, j As Long, k As Long, nn As Long, nCols As Long, nFix As Long, nRows As Long
  3.     Dim rgPT As Range, rgPTvals As Range, rw As Range
  4.     Dim wsDest As Worksheet
  5.     Dim vSource As Variant, vResults As Variant
  6.  
  7. On Error Resume Next
  8.     Application.EnableCancelKey = xlDisabled
  9.  
  10.     With wsSource.Parent
  11.         Set wsDest = .Worksheets(wsSource.Name & "_Data")
  12.         If wsSource Is Nothing Then Exit Sub
  13.  
  14.         If wsDest Is Nothing Then
  15.             Set wsDest = .Worksheets.Add(After:=wsSource)
  16.             wsDest.Name = wsSource.Name & "_Data"
  17.         Else
  18.             wsDest.Cells.ClearContents
  19.         End If
  20.     End With
  21.  
  22. On Error GoTo 0
  23.  
  24.     With wsSource
  25.         Set rgPT = .Range("A2").CurrentRegion
  26.         nCols = Application.Count(rgPT.Rows(2))
  27.         nFix = rgPT.Columns.Count - nCols
  28.         Set rgPTvals = rgPT.Offset(0, nFix).Resize(rgPT.Rows.Count, nCols)
  29.         nRows = rgPT.Rows.Count
  30.     End With
  31.  
  32.         nn = Application.CountIf(rgPTvals, "<>0")
  33.         ReDim vResults(1 To nn + 1, 1 To nFix + 2)
  34.         vSource = rgPT.Value
  35.             For k = 1 To nFix
  36.                 vResults(1, k) = vSource(1, k)
  37.             Next
  38.         vResults(1, nFix + 1) = "Dates"
  39.         vResults(1, nFix + 2) = "Values"
  40.  
  41.         ii = 1
  42.         For i = 2 To nRows
  43.             For j = 1 To nCols
  44.                 If vSource(i, j + nFix) <> 0 Then
  45.                     ii = ii + 1
  46.                     For k = 1 To nFix
  47.                         vResults(ii, k) = vSource(i, k)
  48.                     Next
  49.                     vResults(ii, nFix + 1) = vSource(1, j + nFix)
  50.                     vResults(ii, nFix + 2) = vSource(i, j + nFix)
  51.                 End If
  52.             Next
  53.         Next
  54.  
  55.     wsDest.Cells(1, 1).Resize(nn + 1, nFix + 2).Value = vResults
  56.     wsDest.UsedRange.EntireColumn.AutoFit
  57.     wsDest.Visible = True
  58.         wsDest.Activate
  59.         If wsDest.Range("A1").Value Like "Sale" & "*" Then
  60.             wsDest.Columns("A:A").Select
  61.             Selection.Delete Shift:=xlToLeft
  62.         End If
  63.         If wsDest.Range("A1").Value Like "Res" & "*" Then
  64.             wsDest.Columns("D:D").Select
  65.             Selection.NumberFormat = "m/d/yyyy"
  66.             wsDest.Columns("E:E").Select
  67.             Selection.NumberFormat = "#,##0.00"
  68.         End If
  69.         If wsDest.Name = "SalaryDetail_Data" Then
  70.             wsDest.Columns("c:c").Select
  71.             Selection.NumberFormat = "m/d/yyyy"
  72.             wsDest.Columns("d:d").Select
  73.             Selection.NumberFormat = "#,##0.00"
  74.             wsDest.Visible = xlSheetHidden
  75.         End If
  76. End Sub
Attached Files
File Type: zip SAMPLE DATAFILES.zip (153.7 KB, 55 views)
File Type: zip sample.zip (574.0 KB, 82 views)
Mar 16 '16 #1
1 2923
zmbd
5,501 Recognized Expert Moderator Expert
What I don't see is where you are actually appending anything to the named pivot table.
Two links:
+ Creating PivotTable Reports and Charts with VBA in Excel 2010
This article should still be valid for Ex2013. I include it here so that you can see the basic methodology for working with pivot tables within VBA

Because it sounds like you already have the pivot tables created then you need to really understand:
+ PivotTable Object (Ex2013)
so that you can actually append the data to the desired pivot table.

Once YOU have revised YOUR code post back with the revisions and we'll take a another look.

(You may want to look at this thread too:
Linking tables to make Pivot Table Excel 2010
We were using a workbook as the back-end to the pivot table, and though not ideal, maybe something worth consideration. MORE IMPORTAINTLY, the project shows how to setup and manipulate the pivot tables in VBA!
May 7 '16 #2

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

Similar topics

2
1456
by: Joey Martin | last post by:
I have two tables: customermaster (id,name,email,mailinglists) example: 1,john doe, johndoe@nowhere.com, NULL emailmaster (email,listid) example: johndoe@nowhere.com 1 johndoe@nowhere.com ...
1
23324
by: mojo | last post by:
We have set up an Access database with tables x,y, & z where we would like to have multiple people entering data into a table x. Each person has an identical copy of the database on their PC's. ...
2
16036
by: pob | last post by:
Whats the difference between using a control or a listbox when looping thru a listbox. In example 1 it dims a listbox and an example 2 it dims a control. Please explain. Thanks in advance ...
3
2137
by: chalrav | last post by:
Reading through multiple records, with Loop capability -------------------------------------------------------------------------------- Hi, I have three tables as below: Table: Demand...
3
3594
by: ashwinkpes | last post by:
Hi i am new to ssis and i am trying to transfer data from excel file with multiple workbooks(tables) to oledb destination.......i followed the instructions given in msdn but they r vague and do not...
0
1299
by: chitta | last post by:
Hi I have a problem when i am looping on multiple lines. the question as follows If OrderProductLineItem (DocType='OrderCreate'/'OrderChange') < OrderProductLineItem...
6
2716
by: mahowe | last post by:
Hi, I have had this problem for a while and have not been able solve it. What im looking at doing is looping thru my patient table and trying to organise the patients in to there admission...
0
2211
by: vigneshrao | last post by:
Hi, I have been working on a script that loops through multiple records and sends data (one record per call) to a WS. I am supposed to make a new call for each record before sending the data....
13
4384
by: WU JU | last post by:
Hi. I have thousands of excel files in one directory. I want to build up the Access table from excel files. Each excel file has one worksheet, but I don't need every column and low of the...
5
2120
by: lasilva | last post by:
I have a list of urls that i would like to keep looping thru. Every time the url is opened curtain data is scraped out then posted in correct row and columns. so far I can get my marco to loop thur...
0
7165
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
7205
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
1
6887
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
7379
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
5462
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
1
4910
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new...
0
4590
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
3093
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
3085
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

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.