Share via

Need to import sheets from one Excel file to another using VBA

Anonymous
2012-03-19T21:10:29+00:00

In Excel 2010, I have a series of Excel workbooks with various reports in them. I need to gather them all (including their very unusual formatting) into a single workbook. I've tried simply copy/paste, but the cell colors of the destination sheet are some neon-horrible color, looking nothing at all like the source. So I've decided that I need to do this in VBA in a module, but I don't know how. My exact requirements are:

With a specific set of filenames that will never change....

  • Open a new blank Excel session
  • Open each Excel file, and determine how many sheets there are, and (possibly) the ending row/cell of each sheet.
  • Copy each sheet into the blank workbook
  • When the last sheet from each workbook file is copied, close the source workbook
  • Repeat until all workbooks have been imported
  • Save the destination workbook with all the sheets in it under a specific filename which will include the date

That's it. If someone can point me in the right direction, I would be so grateful. I'm an experienced VBA programer, but very INexperienced with VBA in Excel.

Thanks!!

Dennis

Microsoft 365 and Office | Excel | For home | Windows

Locked Question. This question was migrated from the Microsoft Support Community. You can vote on whether it's helpful, but you can't add comments or replies or follow the question.

0 comments No comments
Answer accepted by question author
  1. Anonymous
    2012-03-24T08:10:08+00:00

    Dennis,

    Try this file also uploaded to my MediaFire account:

    http://www.mediafire.com/?2odd15g05pb61bg

    It's named for_djo1212_Copy1Book.xlsm

    There are 2 buttons on the sheet that both do very much the same thing: allow you to select a workbook and then copy some sheets from it into the workbook.  The difference in the two routines is the way that it copies the formatting from the source workbook.  Hopefully one of the two ways will copy the colors properly.

    You'll need to alter the code to provide the name of a couple of sheets in the workbook you're going to choose for the testing.

    If one of these routines works for you, then we can base more code on that routine.

    Here's the code for the routine I think is going to have the best chance of doing things the way you need them to be done.

    Sub CopyWithSourceFormatting()

      Dim fileChosen As String

      Dim sourceWB As Workbook  'will be the Crystal Reports (CR) created workbook

      Dim sourceWS As Worksheet 'will be a sheet from the sourceWB

      Dim sourceData As Range ' will be used cells on sourceWS

      Dim destWS As Worksheet ' will be the new sheet(s) added to this workbook.

      fileChosen = Application.GetOpenFilename("Excel Files *.xls*, *.xls*", , "Select a File To Process")

      If fileChosen = "False" Then

        'user cancelled file selection

        Exit Sub ' just quit

      End If

      'improve performance and keep screen flickering to a minimum

      Application.ScreenUpdating = False

      'keep from nagging user while opening the other file

      Application.DisplayAlerts = False

      Set sourceWB = Workbooks.Open(fileChosen, False, True) ' open, no link updates, read only

      Application.DisplayAlerts = True

      'the crystal reports workbook is active, make this one active again

      ThisWorkbook.Activate

      '

      'we are going to copy the sheets from the Crystal Reports file

      'one by one, copying the values first and then the formats to

      'see if that helps with keeping the colors true

      '

      'just repeat this section of code as required for each of the sheets

      '

      'set a reference to the sheet in the CR workbook to be copied

    '*************

      Set sourceWS = sourceWB.Worksheets("Sheet1") ' change name as needed

    '*************

      Set sourceData = sourceWS.UsedRange

      'now add a new sheet to this workbook that will be referenced as destWS

      ThisWorkbook.Sheets.Add After:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count)

      Set destWS = ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count)

      sourceData.Copy

      'first copy the values and special number formats

      destWS.Range("A1").PasteSpecial Paste:=xlPasteValuesAndNumberFormats, Operation:=xlNone, _

       skipBlanks:=False, Transpose:=False

      'next copy the "source themes" formatting

      destWS.Range("A1").PasteSpecial Paste:=xlPasteAllUsingSourceTheme, Operation:=xlNone, _

       skipBlanks:=False, Transpose:=False

      Application.CutCopyMode = False

    '

    'repeated section for next sheet all you have to change is the name of sheet to copy from

    '*************

      Set sourceWS = sourceWB.Worksheets("Sheet2") ' change name as needed

    '*************

      Set sourceData = sourceWS.UsedRange

      'now add a new sheet to this workbook that will be referenced as destWS

      ThisWorkbook.Sheets.Add After:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count)

      Set destWS = ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count)

      sourceData.Copy

      'first copy the values and special number formats

      destWS.Range("A1").PasteSpecial Paste:=xlPasteValuesAndNumberFormats, Operation:=xlNone, _

       skipBlanks:=False, Transpose:=False

      'next copy the "source themes" formatting

      destWS.Range("A1").PasteSpecial Paste:=xlPasteAllUsingSourceTheme, Operation:=xlNone, _

       skipBlanks:=False, Transpose:=False

      Application.CutCopyMode = False

    'close the CR workbook

      sourceWB.Close False ' close source workbook without saving changes

    'do final housekeeping cleanup

      Set destWS = Nothing

      Set sourceData = Nothing

      Set sourceWS = Nothing

      Set sourceWB = Nothing

    End Sub

    0 comments No comments

16 additional answers

Sort by: Most helpful
  1. Anonymous
    2012-03-22T18:55:10+00:00

    I couldn't find the buttons, but I put a pair on the sheet myself. Anyway, now there's a really bizarre issue. (BTW, the copy worked perfectly!) On one of the sheets copied into the new workbook, the cell colors are completely messed up. In the source sheet, I have some nice pastel grey and beige cell backgrounds, but after the copy, the cell colors are some horrible bright neon colors. Neon red where the grey was and neon green where the beige was. That the heck? And how can I make sure the source cell colors match when the sheet gets pasted in? Now I'm stumped.

    Any thoughts on how to adjust this? (It did the same thing when I tried to copy by hand in my original testing. Again, no clue as to why.)

    0 comments No comments
  2. Anonymous
    2012-03-21T17:48:43+00:00

    No problem - had enough rain around here to float large cruise ships ourselves, so I understand.

    Let me know how it works out for you.  I actually tested this and it all worked for me here.

    I don't figure you'll use the select files button too often, but thought it would make it easier (and more error free) for you to have it than to have to figure out a way to correctly enter the full paths to some unspecified number of files.

    0 comments No comments
  3. Anonymous
    2012-03-21T16:24:53+00:00

    Sorry for the delay. I was not in the office yesterday due to the danger of flooding at my residence. I am looking at this now and will get back to you soon. THANK YOU for providing this?

    Dennis

    0 comments No comments
  4. Anonymous
    2012-03-20T00:04:24+00:00

    I've prepared a workbook for you - based on what you've asked for it should work except the last step of saving the destination workbook is left up to the user.  I've added a button on the one sheet in it that will, I hope, help you build up the list of files to be processed.  They're saved in column A of the one sheet and you can either add to it or rebuild it completely at any time.

    Here is a link to the file which is located at MediaFire.com in my account's files:

    http://www.mediafire.com/download.php?yy3tddfg5l30ytj

    Here is the code from the workbook, it should work in pretty much any version of Excel.  I realize you're using Excel 2010, but others may want to use it in a pre-2007 version of Excel.

    Sub CopyAllSheetsFromAllBooks()

      Dim destWB As Workbook ' will represent this workbook

      Dim listWS As Worksheet ' will represent Sheet1 (ListSheet) in this workbook

      Dim filesList As Range ' will represent all cells with path\filenames in then

      Dim anyFile As Range ' will represent a single cell with a path\filename in it

      Dim anyLastRow As Long

      Dim maxRows As Long

      Dim sourceWB As Workbook ' will represent each other workbook in turn

      Dim anyWS As Worksheet ' will represent one sheet in the other workbook

      'Assumed 1 sheet in THIS workbook and that it has

      'full path and filenames that are to be processed

      'listed in column A beginning at row 2

      'set references to things in this workbook

      Set destWB = ThisWorkbook

      Set listWS = Sheet1 ' in this workbook

      'here's how to find the last used row in a given column

      'there are times when Rows.Count can cause problems:

      'when running an .xls file in Compatibility mode in Excel 2007/2010

      On Error Resume Next

      Set anyFile = listWS.Range("A" & Rows.Count)

      If Err <> 0 Then

        Err.Clear

        maxRows = 65536 ' assume .xls file

      Else

        maxRows = Rows.Count

      End If

      On Error GoTo 0 ' clear error trapping

      anyLastRow = listWS.Range("A" & maxRows).End(xlUp).Row

      'for an entire sheet you could try listWS.UsedRange.Rows.Count

      'but it can be inaccurate.

      '

      'set up a reference from A2 down to last row with an entry in it

      Set filesList = listWS.Range("A2:A" & anyLastRow)

      'begin working through the list of files

      'this will make things go MUCH faster!

      ' is made TRUE automatically when the Sub ends.

      Application.ScreenUpdating = False

      For Each anyFile In filesList

        'test to make sure it's not an empty cell

        If Not IsEmpty(anyFile) Then

          'make sure the reference is to a valid file

          'for a cell reference, the default property is its .Value

          If Dir$(anyFile) <> "" Then

            'open the file, inhibiting any user prompts

            Application.DisplayAlerts = False

            Set sourceWB = Workbooks.Open(anyFile, False) ' if has links, don't update them

            'work through each worksheet in  the newly opened file

            For Each anyWS In sourceWB.Worksheets

              'copy the sheet to the right end in this workbook

              anyWS.Copy after:=destWB.Worksheets(destWB.Worksheets.Count)

            Next ' end anyWS loop

            'we are done with the other workbook. Close it.

            sourceWB.Close False ' close without saving changes

          End If ' end of test for existing file

        End If ' end of test for empty cell

      Next ' end of anyFile loop

      'the job is done except for cleanup

      'release all used resources back to the system

      'to prevent potential "memory leaks"

      Set sourceWB = Nothing

      Set anyFile = Nothing

      Set filesList = Nothing

      Set listWS = Nothing

      Set destWB = Nothing

      'let the user know they can save this workbook now

      MsgBox "All files have been processed and their sheets have been copied into this workbook.", _

       vbOKOnly + vbInformation, "Task Completed"

    End Sub

    Sub SelectFiles()

      Dim eraseList As Integer

      Dim listWS As Worksheet

      Dim anyLastRow As Long

      Dim fileChosen As String

      Dim maxRows As Long

      Dim testCell As Range

      eraseList = MsgBox("Do you want to start with a clean list (YES)" & _

       vbCrLf & "or add to the existing list (NO)," & _

       vbCrLf & "or don't do anything (CANCEL)?", _

       vbYesNoCancel + vbQuestion, "Start New List?")

      If eraseList = vbCancel Then

        Exit Sub

      End If

      Set listWS = Sheet1

      'there are times when Rows.Count can cause problems:

      'when running an .xls file in Compatibility mode in Excel 2007/2010

      On Error Resume Next

      Set testCell = listWS.Range("A" & Rows.Count)

      If Err <> 0 Then

        Err.Clear

        maxRows = 65536 ' assume .xls file

      Else

        maxRows = Rows.Count

      End If

      On Error GoTo 0 ' clear error trapping

      Set testCell = Nothing ' no longer needed

      If eraseList = vbYes Then

        anyLastRow = listWS.Range("A" & maxRows).End(xlUp).Row + 1

        listWS.Range("A2:A" & anyLastRow).ClearContents

      End If

      'this will loop continuously until the user either

      'clicks the red-x to close the dialog or clicks the [Cancel] button

      Do Until fileChosen = "False"

        fileChosen = Application.GetOpenFilename("Excel Files *.xls*, *.xls*", , "Select a File To Process")

        If fileChosen <> "False" Then

          listWS.Range("A" & maxRows).End(xlUp).Offset(1, 0) = fileChosen

        End If

      Loop

      'all done, do your final cleanup

      Set listWS = Nothing

    End Sub

    0 comments No comments