I like music – lots of different kinds of music, including The Beatles pictured here. These days, I’m more into “Adult Alternative” music, but I still like to listen to some stuff from the ’60’s and ’70’s every now and again.

Around these parts, we get “Breakfast With The Beatles” with Andre Gardner every Sunday from 7am-9am. Check your local listings to see if it is available in your area or you can stream it on KSLX. Really excellent show if you are into The Beatles.

However, today’s post is not about music or The Beatles. It is about Merging Excel Workbooks. Over on the LinkedIn Excel Groups there are many questions about merging data from several Excel Workbooks into 1 Workbook. Many folks suggest linking the workbooks using a formula. Others suggest using the INDIRECT() function. I prefer to use some VBA to copy the desired data from the Source Workbooks to the Destination Workbook.

All testing, screen shots, code in this post are from Office 365. If you are using another version of Excel, your results may vary (though they should not).

Linking Files

A common way to get data from one file to another is to link them. In this sample, I opened 2 Excel files, entered a value in 1 file, activated another file, typed, “=” and clicked on a cell in the 1st file:


DestinationWB.xlsx in the active workbook and cell $A$1 is selected. The formula bar give us:

  1. [SourceWB.xlsx] <- The name of the workbook
  2. Sheet1! <- The name of the worksheet
  3. $A$1 <- The cell reference

When I close the source workbook, the file path is added to the linked cell formula:


The folder location ‘C:\Data\ has been added to the linked formula.

There are a few things I do not like about linked cells

  1. The absolute references were added automatically. If I drag the formula to the right, the formula will still reference $A$1, not $B$1 as we may require
  2. What happens if a Row is added at Row 1 pushing all subsequent rows down by 1? This could cause an error in the linked formula, erroneous results, or at least the need for additional maintenance.
  3. What happens if the source file(s) are moved from the referenced folder location?

Here is the formula with the file in the folder ‘C:\OriginalFolder\.


Linking Files – File Migration

One problem with linking files is that files move in our directory structures from time-to-time. We may initiate this move ourselves as we come up with a new way to organize our file structures. Other times this move may be initiated by the IT Department as they are updating or migrating storage.

Let’s see what happens to the original link formula when I move the source file.
I moved the file from ‘C:\OriginalFolder\ to ‘C:\NewFolder\ in Windows Explorer.


Now when I try to update the link value in the Destination Workbook, I receive an error message


I can click on the change source button, but I would like a solution that provides for as little maintenance needs as possible.

Linking Files – Data Moves On Worksheet

The original linked formula is linked to cell A1 in the source file. What happens if, unbeknownst to you, a user inserts a blank row at A1 and all of the data shifts from A1 to A2?


The Edit Links Dialog status reads, “OK”, but it is not. The Linked Cell formula is still linked to Cell $A$1 and the updated Cell Value is now 0. We could use Find-Replace to update from $1 to $2, but that could have unintended consequences. What if other workbook moved data 2-3 rows? You see the point I’m sure.

Copy Data From Source To Destination

I propose to loop through a folder and copy some data from a worksheet for each workbook found in the folder – I would like the solution to be as dynamic as possible. As I am looping, I will paste the data on a worksheet in Top-Down fashion such that the first file results will be near the top, then the data from the second file and so on.

For today, my source files all have an Excel Table in them, though we could make the process work with Ranges as well with just a bit more work. For additional resources working with Excel Tables, see the links at the bottom of the post.

Some Functions & Properties

First, I’ll look at some VBA functions that I am going to use in the final code. These functions will make your code more dynamic and user-friendly.


CurDir returns the current path. I use CurDir to trap the current path so I can restore it at then before I change the path to make navigating the file structure faster. Use as follows:

Option Explicit

Sub foo2()

    Dim strDirectory As String
    strDirectory = CurDir()
    Debug.Print strDirectory
End Sub




ChDir changes the the current path. I use ChDir to change the current path to get the user closer the final folder they will eventually choose using the FileDialog to select a folder for processing. Use as follows:

Option Explicit

Sub foo2()

    Dim strDirectory As String
    strDirectory = "C:\Data\"
    ChDir (strDirectory)
    Debug.Print CurDir()
End Sub



FileDialog Property

The FileDialog Property of the Application Object returns a FileDialog Object. This give you the ability to interact with users at runtime by allowing the user to choose File(s) or Folder(s) to work with. The FileDialog accepts one argument, the DialogType.

There are 4 DialogTypes in the MsoFileDialogType Enumeration :

  1. msoFileDialogFilePicker
  2. msoFileDialogFolderPicker
  3. msoFileDialogOpen
  4. msoFileDialogSaveAs

For today’s purposes, I’ll use msoFileDialogFolderPicker

Set diaFolder = Application.FileDialog(msoFileDialogFolderPicker)

The Setup…

As I mentioned earlier, each source file has an Excel Table in it. I would like to loop through each file in the source folder and copy the DataBodyRange of the Excel Table to the destination workbook. Additionally, on the first pass, I would also like to copy the HeaderRowRange to create headers in the destination workbook. Lastly, I would like to add some data to the right of the data from the source files, such as the date the data was copied and the name of the source file.

Create Some Sample Data and Files

I quickly whipped up some sample data using Dick’s Random Data Generator and creatively saved the files as File1.xlsx, File2.xlsx, File3.xlsx.


Again, I highlighted the data [Ctrl] + [a] and added an Excel Table [Ctrl] + [t] in each file. I applied a different Table Style to each Table simply to highlight the fact that there are 3 different Tables in 3 different Excel files. If you need to brush up on Excel Tables or need to start at the beginning:

  1. Excel Table Tutorial – Contextures
  2. Sur la Excel Table
  3. Listing Toward ListObjects

Loop Through Files In A Folder

When I need to loop through files in a folder – I use the FileSystemObject (FSO). The FileSystemObject is a top-level object in the Microsoft Scriping Runtime Library (Scrrun.dll). Here are some additional references if you need to brush up or are not familiar with FSO.

  1. JP Software Tech
  2. Chip Pearson
  3. 4 Guys From Rolla
  5. MSDN

edit: I am going to use Late Binding in the sample snippets below. A discussion on Late / Early Binding is beyond the scope of this post. Please see the “Additional Resources” at bottom for links to detailed explanation of Late / Early Binding.

Copying Data From Source To Destination

It’s finally time to copy the data from the source workbooks to the destination workbook. I’m using three files with 50 records each, but you could use this code with an unlimited number of records or variable number of records and unlimited number of files (3, 10, 50,…) – as long as you do not exceed 1,048,576 rows (though I would never use that many row in Excel – time to consider a database).

Option Explicit

Sub CopyDataFromSourceFiles()
    'Author         :           Winston Snyder
    'Created Date   :           1/26/2014
    'Comments       :           Assumes each source file contains at least one list object (Excel Table)
    'Delare variables
        Dim wb                  As Workbook
        Dim wbData              As Workbook
        Dim ws                  As Worksheet
        Dim wsData              As Worksheet
        Dim rngData             As Range
        Dim rngDestination      As Range
        Dim lo                  As ListObject
        Dim fso                 As Object
        Dim fsoFolder           As Object
        Dim fsoFile             As Object
        Dim strSelectedFolder   As String
        Dim strCurrentPath      As String
        Const strSpecifiedPath  As String = "C:\"
        Dim lngRows             As Long
        Dim blnFlag             As Boolean
    'Excel environment - speed things up
        With Application
            .ScreenUpdating = False
            .DisplayAlerts = False
            .EnableEvents = False
            .Calculation = xlCalculationManual
        End With
    'Initialize variables
        Set wb = ThisWorkbook
        Set ws = wb.Worksheets("Data")
        blnFlag = True
    'Clear data from control workbook from previous consolidations
    'Get the current path, so reset the path at the end of the procedure
        strCurrentPath = CurDir()
    'Set the target directory to get the user closer to the working folder
    'This will minimize the time the user must spend drilling into the file system
    'once they are presented with the FileDialog
        ChDir (strSpecifiedPath)
    'Create a FileSystemObject
        Set fso = GetFSO

    'Prompt the user to select a folder
    'Return the path of the selected folder
        strSelectedFolder = GetSelectedFolder
    'Get the FSO Folder of the selected folder
        Set fsoFolder = fso.GetFolder(strSelectedFolder)
    'Loop each file in folder
    'Copy data from each file to control workbook
        For Each fsoFile In fsoFolder.Files
            Debug.Print fsoFile.Name
            Set wbData = Workbooks.Open(fsoFile)
            Set wsData = wbData.Worksheets("Sheet1")
            'Get next blank row from destination worksheet
            'If first time, need row 1, else, next blank row
                lngRows = GetRows(ws:=ws)
                If blnFlag = False Then lngRows = lngRows + 1
            'The Destination Range
                Set rngDestination = ws.Cells(lngRows, 1)
            'If first time, include the header row
                With wsData
                    For Each lo In .ListObjects
                        If blnFlag = True Then
                            Set rngData = Union(lo.HeaderRowRange, lo.DataBodyRange)
                            blnFlag = False
                            Set rngData = lo.DataBodyRange
                        End If
                    Next lo
                End With
            'Copy the Data Range to the Destination Range
                rngDestination.PasteSpecial xlPasteValuesAndNumberFormats
            'Close the source file
        Next fsoFile
    'Tidy up
        'Restore to original path
            ChDir (strCurrentPath)
        'Restore Excel environment
            With Application
                .ScreenUpdating = True
                .DisplayAlerts = True
                .EnableEvents = True
                .Calculation = xlCalculationAutomatic
            End With
        'Destroy objects
            Set fsoFolder = Nothing
            Set fso = Nothing
            Set rngData = Nothing
            Set rngDestination = Nothing
            Set ws = Nothing
            Set wb = Nothing
End Sub
Private Function GetRows(ws As Worksheet) As Long

    Dim r       As Long
    With ws
        r = .Cells(Rows.Count, 1).End(xlUp).Row
        GetRows = r
    End With
End Function
Private Function GetFSO()

    Dim fso             As Object
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set GetFSO = fso
    Set fso = Nothing

End Function
Private Function GetSelectedFolder() As String
    Dim diaFolder       As FileDialog
    Dim strFolder       As String

    Set diaFolder = Application.FileDialog(msoFileDialogFolderPicker)
    With diaFolder
        .AllowMultiSelect = False
        strFolder = .SelectedItems(1)
    End With

    GetSelectedFolder = strFolder
End Function


I formatted the output and hid some rows to show that there are 151 records as expected (3 files * 50 records each + 1 header row).

My favorite part of the code is here

'If first time, include the header row
                With wsData
                    For Each lo In .ListObjects
                        If blnFlag = True Then
                            Set rngData = Union(lo.HeaderRowRange, lo.DataBodyRange)
                            blnFlag = False
                            Set rngData = lo.DataBodyRange
                        End If
                    Next lo
                End With

The properties of the ListObject (Excel Table) such as HeaderRowRange and DataBodyRange are 2 reasons why the ListObject is far superior to the Range Object. Couple these kinds of properties with the fact that you can move the Excel Table anywhere on the worksheet you want and add rows to the Table or redact rows from the Table and the consolidation code will still work flawlessly. No Excel Hell! Awesome!

Tidy Up

, , , , , , ,


My grasp of all things maritime is limited:

  1. I love seafood (Scallops with garlic, butter and white wine – I’m looking at you)
  2. I can still tie a few knots I learned in Scouts
  3. I enjoy The Pirates of the Caribbean Ride at Disney World
  4. I can speak like a pirate. (International Speak Like a Pirate Day is Friday, September 19, 2014. So set yer reminder on yer calendar on yer mobile device now matey, arrrrgghhh!)

Today’s post, however, is not about my favorite ale or the Jolly Roger. It is about the ListObjects Object and / or ListObject Object of the Excel Object Model. There is no typo there – though admittedly it does look and sound a little odd. Links to the Object Models are at the bottom of this post.

Convert a ListObject To A Range

I’ll begin by converting an Excel Table (ListObject) that I created in my last post back to a Range. Warning: Converting an Excel Table to a Range will wreak havoc on any Structured Reference formulas that are using the Excel Table Do not try this on any production models, use test workbooks only until you have a full understanding on the outcomes.

Unlist The Excel Table

Option Explicit

Sub ConvertListObjectToRange_1()
    'Purpose:   Unlist an Excel Table to convert it to a range

    Dim wb As Workbook
    Dim ws As Worksheet
    Dim lo As ListObject
    Set wb = ThisWorkbook
    Set ws = wb.Worksheets("Data")
    For Each lo In ws.ListObjects
    Next lo
    Set ws = Nothing
    Set wb = Nothing

End Sub


  1. The filter arrows are gone
  2. When I click on a cell within the Range, the Table Tools Tab no longer activates

The Excel Table has been converted to a Range. But I would also like to remove all formatting that was introduced by the Excel Table.

Remove Formatting Left By Excel Table

I would like to remove the these formats:

  1. Remove all color
  2. Remove all borders
  3. Make sure all font colors are black
  4. Make sure all fonts are normal (not bold)
Sub RemoveFormatting()
    'Purpose:   Remove formatting left from Excel Table

    Dim wb As Workbook
    Dim ws As Worksheet
    Dim rng As Range
    Set wb = ThisWorkbook
    Set ws = wb.Worksheets("Data")
    Set rng = ws.Range("A1").CurrentRegion
    With rng
        .Interior.ColorIndex = xlColorIndexNone
        .Borders.LineStyle = xlLineStyleNone
    End With
    With ws
        .Range("A1").EntireRow.Font.Color = vbBlack
        .Range("A1").EntireRow.Font.Bold = False
    End With
    Set rng = Nothing
    Set ws = Nothing
    Set wb = Nothing
End Sub

Looks good – all cleaned up! Next, I’ll look at adding a ListObject (Excel Table) using VBA

A Quick Segue – Table Styles

In my code for adding the Excel Table, I will want to add a Table Style so let’s look at some code to list available styles:

Sub ListTableStyles()
    'Purpose:   List all Table Styles in the workbook
    'Comment:   [Ctrl] + [G] to activate the immediate window to view the output

    Dim wb As Workbook
    Dim ts As TableStyle
    Set wb = ActiveWorkbook
    With wb
        For Each ts In .TableStyles
            Debug.Print ts.Name
        Next ts
    End With
    Set wb = Nothing
End Sub

Now I have a list of all available styles in the workbook as well as the correct naming convention to be used.

Convert A Range To A ListObject (Excel Table)

Now I am ready to convert the Range back to a ListObject (Excel Table)

Sub ConvertRangeToTable()
    Dim wb As Workbook
    Dim ws As Worksheet
    Dim rng As Range
    Dim lo As ListObject
    Set wb = ThisWorkbook
    Set ws = wb.Worksheets("Data")
    Set rng = ws.Range("A1").CurrentRegion

    Set lo = ws.ListObjects.Add(SourceType:=xlSrcRange, _
                                Source:=rng, _
                                TableStyleName:="TableStyleMedium4", _
    lo.Name = "tblData"
    Set lo = Nothing
    Set rng = Nothing
    Set ws = Nothing
    Set wb = Nothing
End Sub

Looks great! I now have an Excel Table named, “tblData”. There are additional Source Types that may be used as a source for the Excel Table: Source Type Enumeration. I will look at these in future posts.

ListObject Business Case

A fairly common request over on the LinkedIn Excel Groups is how to copy filtered data without the header row to another Worksheet or Range. This can be accomplished with a Range Object and a few manipulations to shape the data. But it is much easier with ListObjects.
The ListObject offers three distinct Ranges that may be exploited in VBA:

The HeaderRowRange


The DataBodyRange


The TotalsRowRange

For today, I will focus on the DataBodyRange. I want to filter the data and copy the Rows that remain except for the HeaderRowRange.

Sub FilterTable()
    'Purpose:   Filter Excel Table, copy visibile range

    Dim wb As Workbook
    Dim ws As Worksheet
    Dim rng As Range
    Dim lo As ListObject
    Const strCriteria As String = "Aetna"
    Set wb = ThisWorkbook
    Set ws = wb.Worksheets("Data")
    Set rngDestination = ws.Range("G3")
    With ws
        For Each lo In .ListObjects
            'DataBodyRange to Range
                Set rng = lo.DataBodyRange
            'Filter the Range
                rng.AutoFilter _
                    Field:=1, _
            'Copy the visible range
                rngDestination.PasteSpecial xlPasteValuesAndNumberFormats
        Next lo
    End With

    Set rngDestination = Nothing
    Set rng = Nothing
    Set ws = Nothing
    Set wb = Nothing
End Sub

Looks great! Quite a bit easier than jumping through some gyrations to reshape the data to remove the header row from the visible range.

I use the SpecialCells Method of the Range Object here to copy just the visible range. I covered this previously in ,this post

Tidy Up

    Final Thoughts

    That’s it for today. I hope you find this post helpful and are able to go through fewer gyrations in the future to shape your data. Now, where’d I put my parrot and wooden leg?


    Download the file from Skydrive

, , , ,


Generally, I’m an easy-going guy – very content with a good burger and a good brew. Every now and again, however, it’s fun to put on my fines and kick up my heels.

I’ve worked as a controller (spreadsheet jockey) for a few food service companies, so I have been around and pitched in on more than a few catering events. I’m here to tell you, it’s tough work, with excruciatingly long hours on your feet. I’m used to shining a seat, not being on my feet for 10-12 hours at a clip.

So, next time you’re at a great event, make sure you let the folks doing the heavy lifting that you appreciate their hard work so that you can have a good time.

Today’s post, however, is not about extraordinary events and culinary creations. This post is about Excel Tables – an underused feature in Excel. Over on the LinkedIn Excel Groups, Craig Hatmaker is leading the charge to make more folks aware of Excel Tables and their advantages. I’m curious as why more folks do not use Excel Tables? I look forward to any all comments below as to why this may be.

Create An Excel Table

You may Get External Data from Access, SharePoint, etc… and the resulting data in Excel will be presented in an Excel Table automatically. For now, I will simply create an Excel Table from a Range. However, in production these days, I keep all data external from Excel in Access, SharePoint or SQL Database.

I cooked up some data using a Random Data Generator from Dick Kusleika over at Daily Dose of Excel. I added some formatting to make it more palatable on a web browser. Now I want to convert the Range into an Excel Table.


I clicked on any cell in the Range, clicked on the Insert Tab on the Ribbon and clicked on the Table icon in the Tables Group as indicated by the arrow in the screen shot. If you are a keyboard person, you may press [Ctrl] + [T] to activate the Create Table Dialog.


The continuous range is automatically selected as indicated by the “dancing ants”. The Create Table Dialog opens. The Range Selection Tool displays the selected range while also allowing you to use the selector tool to select your own range should you choose to do so. The “My table has headers” checkbox is ticked automatically.


Click “Ok” when you are finished and your Range is converted into an Excel Table. The default Table Style is applied to the table


Ribbon – Design Tab : Table Tools

When you click on an Excel Table, the Design Tab : Table Tools becomes active on the Ribbon. The Design Tab : Table Tools gives you many tools for working with properties styles and options of the Excel Table. The tab disappears when you are not clicked on a cell in the Excel Table.



Excel Table – Name

Please note in the first screen shot of the Ribbon, in the Properties Group, the name of the Excel Table is Table2. You may change this and I recommend you do to something more meaningful. For demonstration purposes, I’ll name this Excel Table -> tblRevenues.

Structured References – Calculated Columns

Let’s take a look at adding a calculation to the Excel Table. Suppose we want to know what happens to Total Revenue if we increase it by 10 %. I move to the next available column, and enter a description in the header row


Look at what happens when I confirm the description in the header row by pressing enter. The Table Style formatting is automatically filled down the new column.


Now I need to enter a formula to increase the Total Revenue of each row by 10 %. In cell E2, I enter = and click on D2, Excel enters the Column Specifier, “[@TotalRevenue]” for me.


I complete the formula by multiplying by 1.1, pressing enter, and then using the fill handle in the lower right corner of the cell to send the formula down.


Look Ma’ – No Dynamic Ranges

One of the most frequent errors we read about is data being missed by a formula using by a cell reference formula: =SUM(Sheet1!$A$2:$A$10)

One way around this is to use Dynamic Named Ranges (DNR). Daniel Ferry shows us how to create DNR’s using the INDEX() function in his epic post, The Imposing Index. Definitely check it out.

But with Excel Tables, we do not need to create Dynamic Named Ranges. As we add data to the Excel Table it is added to the table and included in any analyses of the data.

Structured Reference – Analytical Example

Let’s suppose we are interested in a summary total based on a few criteria such as company name, account number and date range. We can use the SUMIFS() function with our Excel Table and Structured references instead of cell references:



What happens if I add 1 more record that meets all of the criteria for $1,000? Wblanke expect the new total to be $10,562.36.



Perfect! $10,562.36 as expected.

Does The Formula Make Your Eyeballs Spin?

Let’s take another look.


Kris Szabo once commented on one of the LinkedIn Groups that the formula made her eyeballs spin. Fair enough – Let’s try wrapping the formula to see if that makes it easier to read.

  • Click on the cell with the formula so that the formula is visible in the formula bar
  • Move the cursor to the beginning of each occurrence of the table name, “tblData”
  • Press [Alt] + [Enter] on the keyboard to force all subsequent text to the next line
  • Press [Spacebar] to move the text until it is in the correct column

When complete, this is what the formula should look like in the formula bar


Much easier to read – what do you think?

The Peter Principle – Update Sept. 6, 2014

Over on the ExcelHero Group on LinkedIn, Peter Bartholomew correctly pointed out that we may use a 2nd Excel Table and then refer to the variable components through the use of the Table Object Nomenclature instead of using the cell references as I did above.

The revised formula using the Table Object Nomenclature:

= SUMIFS( tblData[Amount], 
          tblData[Company], "=" & [@Company], 
          tblData[Account], "=" & [@Account], 
          tblData[Date], ">=" & [@StartDate], 
          tblData[Date], "<=" & [@EndDate] 

My take:

I like the 2 Table approach. However, the horizontal (ColumnWise) layout does not feel natural. Many, perhaps most, user-input forms are designed with a vertical (RowWise) layout.

Additionally, in some reporting situations, we may want to refer to the same criteria without repeating the criteria (Some folks find the repetition “ugly” or at least “irritating”). For example we may want to hold constant “Company” and “Account” through the use of Absolute References while varying the Start and End dates to examine account balances through the periods of the fiscal year or some span of time.

Is This A Segue To DAX?

DAX is Dynamic Analysis eXpressions. It is the formula language behind Data Models with Power Pivot as well as a query language for working with Tabular Databases. Here is a very simple DAX Formula that I borrowed from Chandoo’s site: SUM(sales[sale amount]). Looks a lot like the syntax for Structured References – doesn’t it? I’m not saying that if you know Excel Tables w/ Structured References that you will know everything there is to know about DAX. I’m simply saying that if you can work with Excel Tables w/ Structured References, it will help you understand DAX a bit more.

Next Up – VBA for Excel Tables (ListObjects)

I covered Excel Tables here as a precursor to looking into the ListObject Object Model in VBA. The ListObject is parlance in VBA for Excel Tables – I suspect a holdover from Lists the original name for Excel Tables when they were first introduced in Excel 2003. Have a look at the Members (Properties and Methods) of the ListObject Object Model and stay tuned for my next post on ListObjects.

Tidy Up

    Final Thoughts

    That’s it for now. I really like Excel Tables and I think you will like them even more once I show some VBA code for ListObjects. Remember, Excel Tables and ListObjects are the same thing.

    There are several nice features about Excel Tables, but for me the best part is automatically adding data to the table so that all data is included in any analyses. What do you like most?

, , ,