Merge multiple xlsx and xls files into one workbook - excel

I have many xlsx and xls files in a folder containing 2-3 worksheets in each file. I want to merge all these files into one workbook. I have a sample code but it is not merging xlsx file, it is picking only xls files of the selected folder. Sample code is mentioned below. Help me
Sub MergeFiles ()
Dim numberOfFilesChosen, i As Integer
Dim tempFD As FileDialog
Dim mainWb, sourceWb As Workbook
Dim tempWS As Worksheet
Set mainWb = Workbooks.Add 'Application.ActiveWorkbook
Set tempFD = Application.FileDialog(msoFileDialogFilePicker)
'Allow the user to select multiple workbooks
tempFD.AllowMultiSelect = True
numberOfFilesChosen = tempFD.Show
'Loop through all selected workbooks
For i = 1 To tempFD.SelectedItems.Count
'Open each workbook
Workbooks.Open tempFD.SelectedItems(i)
Set sourceWb = ActiveWorkbook
'Copy each worksheet to the end of the main workbook
For Each tempWS In sourceWb.Worksheets
tempWS.Copy after:=mainWb.Sheets(mainWb.Worksheets.Count)
Next tempWS
'Close the source workbook
sourceWb.Close
Next i
End Sub

Your code does work without any problems with a small amount of xls, xlsx and xlsb files.
I've tried with 24 different files.
Sub MergeFiles()
Application.ScreenUpdating = False ' **** Gain some performance?
Dim numberOfFilesChosen, i As Integer
Dim tempFD As FileDialog
Dim mainWb, sourceWb As Workbook
Dim tempWS As Worksheet
Set mainWb = Workbooks.Add 'Application.ActiveWorkbook
Set tempFD = Application.FileDialog(msoFileDialogFilePicker)
'Allow the user to select multiple workbooks
tempFD.AllowMultiSelect = True
numberOfFilesChosen = tempFD.Show
'Loop through all selected workbooks
For i = 1 To tempFD.SelectedItems.Count
'Open each workbook
Workbooks.Open tempFD.SelectedItems(i)
Set sourceWb = ActiveWorkbook
' Application.ScreenUpdating = True '****** Uncomment to get more feedback
' mainWb.Activate
' mainWb.Sheets(1).Range("A1").EntireRow.Insert
' mainWb.Sheets(1).Range("A1").Value = sourceWb.Name
' Debug.Print sourceWb.Name
' Application.ScreenUpdating = True
'Copy each worksheet to the end of the main workbook
For Each tempWS In sourceWb.Worksheets
tempWS.Copy after:=mainWb.Sheets(mainWb.Worksheets.Count)
Next tempWS
'Close the source workbook
sourceWb.Close
Next i
Application.ScreenUpdating = True ' **** Gain some performance?
End Sub

Related

Macro to Copy/Paste data from txt files into new workbook is pasting into the Personal Workbook

The title more or less sums it up. I am trying to make a simple macro to open and then copy/paste data from txt files into a newly opened workbook. What I have work but it pastes it into the Personal Workbook at that opens before a new "Book1". I could make it paste to Book1 but I just want it paste it into the first workbook opened in case I want to add more data to the same file down the road. I am pretty new to this so any help would be greatly appreciated!!
Public Sub ImportFile()
Dim TextFile As Workbook
Dim OpenFiles() As Variant
Dim x As Integer
OpenFiles = Application.GetOpenFilename(Title:="Select File(s) to Import", MultiSelect:=True)
For x = 1 To Application.CountA(OpenFiles)
Set TextFile = Workbooks.Open(OpenFiles(x))
TextFile.Sheets(1).Range("A1").CurrentRegion.Copy
Workbooks(1).Activate
Workbooks(1).Worksheets.Add
ActiveSheet.Paste
TextFile.Close
Next x
End Sub
It will create a new workbook. It will create additional worksheets with names "New1, New2 " etc. Hope it will help your requirement
Public Sub ImportFile()
Dim TextFile As Workbook
Dim OpenFiles() As Variant
Dim x As Integer
Dim wb As Workbook
Dim ws As Worksheet
Set wb = Workbooks.Add
OpenFiles = Application.GetOpenFilename(Title:="Select File(s) to Import", MultiSelect:=True)
For x = 1 To Application.CountA(OpenFiles)
i = 1
Set ws = wb.Sheets.Add
Set TextFile = Workbooks.Open(OpenFiles(x))
TextFile.Sheets(1).Range("A1").CurrentRegion.Copy
ws.Paste
Application.CutCopyMode = False
Application.CutCopyMode = True
ws.Name = "New" & i
i = i + 1
TextFile.Close
Next x
End Sub
Try the next code line, please:
Debug.Print Workbooks(1).Name
It will return "PERSONAL.XLSB".
So, if you use your code like it is, it will all the time copy in "PERSONAL.XLSB".
If you do not want using a new workbook and you like your initial approach, you can try:
'...
'your existing code
TextFile.Sheets(1).Range("A1").CurrentRegion.Copy
Dim wb As Workbook, ws As Worksheet
If Workbooks.count > 1 Then
Set wb = Workbooks(2)
Else
Set wb = Workbooks.Add
End If
Set ws = wb.Worksheets.Add
'and always use this sheet to copy on it...
'your existing code...
'...

Naming sheets with workbook name after merging?

I've got over 200 workbooks that I need to merge, the code below will merge the workbooks and add all the sheets into one workbook.
In that workbook the sheets are being named Sheet 1 (1), Sheet 1 (2) and so on.
If the sheet was copied from Workbook1 the sheet name would be workbook 1
Sub mergeFiles()
'Merges all files in a folder to a main file.
'Define variables:
Dim numberOfFilesChosen, i As Integer
Dim tempFileDialog As FileDialog
Dim mainWorkbook, sourceWorkbook As Workbook
Dim tempWorkSheet As Worksheet
Set mainWorkbook = Application.ActiveWorkbook
Set tempFileDialog = Application.FileDialog(msoFileDialogFilePicker)
'Allow the user to select multiple workbooks
tempFileDialog.AllowMultiSelect = True
numberOfFilesChosen = tempFileDialog.Show
'Loop through all selected workbooks
For i = 1 To tempFileDialog.SelectedItems.Count
'Open each workbook
Workbooks.Open tempFileDialog.SelectedItems(i)
Set sourceWorkbook = ActiveWorkbook
'Copy each worksheet to the end of the main workbook
For Each tempWorkSheet In sourceWorkbook.Worksheets
tempWorkSheet.Copy after:=mainWorkbook.Sheets(mainWorkbook.Worksheets.Count)
Next tempWorkSheet
'Close the source workbook
sourceWorkbook.Close
Next i
End Sub
Add this in you For Each loop
Dim j as integer ‘Add to top of your sub
j = 0 ‘Add inside for loop
For Each tempWorkSheet In sourceWorkbook.Worksheets
j= j+1
tempWorkSheet.Copy after:=mainWorkbook.Sheets(mainWorkbook.Worksheets.Count)
ActiveSheet.Name = sourceWorkBook.Name & “ - “ & j ‘Added Line of code to rename copied tab
Next tempWorkSheet
As long as your workbook names aren’t too long or duplicate, it should be good
Merge Files
Code Issues
You have declared numberOfFilesChosen as Variant:
Dim numberOfFilesChosen, i As Integer ' Wrong
Dim numberOfFilesChosen as Integer, i As Integer ' OK
You have declared mainWorkbook as Variant:
Dim mainWorkbook, sourceWorkbook As Workbook ' Wrong
Dim mainWorkbook as Workbook, sourceWorkbook As Workbook ' OK
Such a code should be in the Workbook (mainWorkbook) where the
Worksheets are being imported, so you don't need a variable, just use
ThisWorkbook. Then in combination with the With statement, you
can use e.g. .Sheets(.Sheets.Count).
You are changing between sheets and worksheets. When you use mainWorkbook.Worksheets.Count, this might not necessarily be the last sheet, so it would be more correct to use mainWorkbook.Sheets.Count especially for the added sheet counter to function correctly.
tempWorkSheet.Copy after:=mainWorkbook.Sheets(mainWorkbook.Worksheets.Count)
tempWorkSheet.Copy after:=mainWorkbook.Sheets(mainWorkbook.Sheets.Count) ' Preferable
When you use sourceWorkbook.Close, you might be asked to save the workbook. Using
sourceWorkbook.Close False ' Preferable
will close the workbook without saving changes.
The code will fail if you run it another time, because the sheet names
it will try to create are the same. Therefore I have added
DeleteWorksheetsExceptOne which I used while testing the code.
The Code
Sub mergeFiles()
'Merges all files in a folder to a main file.
'Define variables:
Dim tempFileDialog As FileDialog
Dim sourceWorkbook As Workbook
Dim tempWorkSheet As Worksheet
Dim numberOfFilesChosen As Long, i As Long, j As Long
Set tempFileDialog = Application.FileDialog(msoFileDialogFilePicker)
'Allow the user to select multiple workbooks
tempFileDialog.AllowMultiSelect = True
numberOfFilesChosen = tempFileDialog.Show
With ThisWorkbook
'Loop through all selected workbooks
For i = 1 To tempFileDialog.SelectedItems.Count
'Open each workbook
Workbooks.Open tempFileDialog.SelectedItems(i)
Set sourceWorkbook = ActiveWorkbook
j = 0
'Copy each worksheet to the end of the main workbook
For Each tempWorkSheet In sourceWorkbook.Worksheets
j = j + 1
tempWorkSheet.Copy After:=.Sheets(.Sheets.Count)
' Rename newly added worksheet to the name of Source Workbook
' concatenated with "-" and Counter (j).
.Sheets(.Sheets.Count).Name = sourceWorkbook.Name & "-" & j
Next
'Close the source workbook. False for not saving changes.
sourceWorkbook.Close False
Next
End With
End Sub
Delete All Worksheets But One
'*******************************************************************************
' Purpose: Deletes all Worksheets in the ActiveWorkbook except one.
' Danger: This code doesn't ask anything, it just does. In the end you will
' end up with just one worksheet (cStrWsExcept) in the workbook
' (cStrWbPath). If you have executed this code and the result is not
' satisfactory, just close the workbook and try again or don't. There
' will be no alert like "Do you want to save ..." because of the line:
' ".Saved = True" i.e. "objWb.Saved = True".
' Arguments (As Constants):
' cStrWbPath
' The path of the workbook to be processed. If "", then ActiveWorkbook is
' used.
' cStrWsExcept
' The worksheet not to be deleted. If "", then the Activesheet is used.
'*******************************************************************************
Sub DeleteWorksheetsExceptOne()
Const cStrWbPath = "" ' if "" then ActiveWorkbook
Const cStrWsExcept = "Sheet1" ' if "" then ActiveSheet
Dim objWb As Workbook
Dim objWsExcept As Worksheet
Dim objWsDelete As Worksheet
If cStrWbPath = "" Then
Set objWb = ActiveWorkbook
Else
Set objWb = Workbooks(cStrWbPath)
End If
With objWb
If cStrWsExcept = "" Then
Set objWsExcept = .ActiveSheet
Else
Set objWsExcept = .Worksheets(cStrWsExcept)
End If
' To suppress the "Data may exist in the sheet(s) selected for deletion.
' To permanently delete the data, press Delete." - Alert:
Application.DisplayAlerts = False
For Each objWsDelete In .Worksheets
If objWsDelete.Name <> objWsExcept.Name Then
objWsDelete.Delete
End If
Next
' To suppress the "Do you want to save changes you made to ... ?" - Alert:
.Saved = True
Application.DisplayAlerts = True
End With
End Sub
'*******************************************************************************

VBA/Excel - Copy worksheet to another workbook (Replace existing values)

I am trying to copy the values from one sheet, into another workbooks sheet. However I can't get Excel to actually paste the values to the other workbook.
This my code.
Sub ReadDataFromCloseFile()
On Error GoTo ErrHandler
Application.ScreenUpdating = False
Dim src As Workbook ' SOURCE
Dim currentWbk As Workbook ' WORKBOOK TO PASTE VALUES TO
Set src = openDataFile
Set currentWbk = ActiveWorkbook
'Clear existing data
currentWbk.Sheets(1).UsedRange.ClearContents
src.Sheets(1).Copy After:=currentWbk.Sheets(1)
' CLOSE THE SOURCE FILE.
src.Close False ' FALSE - DON'T SAVE THE SOURCE FILE.
Set src = Nothing
ErrHandler:
Application.EnableEvents = True
Application.ScreenUpdating = True
End Sub
And below is the function openDataFile which is used to get the source workbok (File Dialog):
Function openDataFile() As Workbook
'
Dim wb As Workbook
Dim filename As String
Dim fd As FileDialog
Set fd = Application.FileDialog(msoFileDialogFilePicker)
fd.AllowMultiSelect = False
fd.Title = "Select the file to extract data"
' Optional properties: Add filters
fd.Filters.Clear
fd.Filters.Add "Excel files", "*.xls*" ' show Excel file extensions only
' means success opening the FileDialog
If fd.Show = -1 Then
filename = fd.SelectedItems(1)
End If
' error handling if the user didn't select any file
If filename = "" Then
MsgBox "No Excel file was selected !", vbExclamation, "Warning"
End
End If
Set openDataFile = Workbooks.Open(filename)
End Function
When I try to run my Sub, it opens the src file and just stops there. No values are copied and pasted to my currentWbk
What am I doing wrong?
Maybe my sub will help u
Public Sub CopyData()
Dim wb As Workbook
Set wb = GetFile("Get book") 'U need use your openDataFile here
Dim wsSource As Worksheet
Set wsSource = wb.Worksheets("Data")'enter your name of ws
Dim ws As Worksheet
Set ws = ThisWorkbook.Worksheets.Add
wsSource.Cells.Copy ws.Cells
wb.Close False
End Sub

Copying between workbooks and worksheets

I am trying to do a copy and paste of data in between workbooks and worksheets. I have the following codes but it seems to be taking up much time. I was wondering if there is any simpler way in copying?
Sub Test1()
Dim wb As Workbook, x As String, y As String, wb1 As Workbook
For Each wb In Application.Workbooks
If wb.Name <> ThisWorkbook.Name Then x = wb.Name
Next wb
Workbooks(x).Activate
Sheets("Sheet1").Range("A:E").Copy
ActiveWindow.WindowState = xlMinimized
Sheets("Sheet1").Range("A1").Select
Selection.PasteSpecial Paste:=xlPasteAll
Sheets("Sheet1").Range("A1").Select
Workbooks(x).Activate
ActiveWindow.WindowState = xlNormal
Sheets("Sheet1").Range("F:F").Copy
ActiveWindow.WindowState = xlMinimized
Sheets("Sheet1").Range("G:G").Select
Selection.PasteSpecial Paste:=xlPasteAll
Workbooks(x).Activate
ActiveWindow.WindowState = xlNormal
End Sub
Some headsup:- Use
Sub Test1()
Application.Screenupdating = False
'yourcode
Application.Screenupdating = True
End Sub
in your code to execute it faster
for copy paste a short verion that can be used is
Sheets("Sheet1").Range("F:F").Copy Sheets("Sheet1").Range("G:G")
Instead of activating certain books try pasting directly to the destination as mentioned in the above code.
you can remove "ActiveWindow.WindowState = xlMinimized"
EDIT:- as per added comments
dim wb1 as workbook
dim wb2 as workbook
set wb1 = ("Filename.xlsx")
set wb2 = ("filename.xlsx")
wb1.sheetname.range("A1").copy wb2.sheetname.range("A1")
you can further decalre your sheetname as well
dim ws as worksheet
set ws = worksheets("Sheetname")
Edit as per second comment (add variable to newly opened workbook)
Dim path as variant
dim wsb as workbook
path = \\C:your path ' not the sheet name
Set wsb = Workbooks.Open(filename:=myfolder & "\" & "filename".xlsm")
'your codes
I got some idea from JMAX and found a way which is as follows:
Sub test()
Dim wb As Workbook, wb2 As Workbook
Dim ws As Worksheet
Dim vFile As Variant
'Set source workbook
Set wb = ActiveWorkbook
'Open the target workbook
vFile = Application.GetOpenFilename("Excel-files,*.xls", _
1, "Select One File To Open", , False)
'if the user didn't select a file, exit sub
If TypeName(vFile) = "Boolean" Then Exit Sub
Workbooks.Open vFile
'Set targetworkbook
Set wb2 = ActiveWorkbook
'For instance, copy data from a range in the first workbook to another range in the other workbook
wb2.Worksheets("Sheet1").Range("A:B").Copy
wb.Worksheets("Sheet1").Activate
wb.Worksheets("Sheet1").Range("A1").PasteSpecial Paste:=xlPasteAll
End Sub

Copying external Excel sheet to current workbook using VBA

I'm working on small project in which I need to add sheets to the currently open workbook from any external database of worksheets in another workbook. I made a form to import any sheet that is required in the currently open (active) workbook.
The sheets will be copied from remote (in any other folder but same computer) workbook. I am using following code but due to unknown reasons the sheets are NOT getting copied to my current workbook.
Dim wb As Workbook
Dim activeWB As Workbook
Dim FilePath As String
Dim oWS As String
Set activeWB = Application.ActiveWorkbook
FilePath = "D:\General Required Docs\DATA.xlsm"
If optFirst.Value = True Then
Application.ScreenUpdating = False
Application.DisplayAlerts = False
On Error Resume Next
oWS = cboMaterial.Value
Set wb = Application.Workbooks.Open(FilePath)
wb.Worksheets(oWS).Copy
After:=Application.ActiveWorkbook.Sheets(ThisWorkbook.Sheets.count)
activeWB.Activate
wb.Close False
Application.ScreenUpdating = True
Application.DisplayAlerts = True
Change
wb.Worksheets(oWS).Copy
After:=Application.ActiveWorkbook.Sheets(ThisWorkbook.Sheets.count)
to
wb.Worksheets(oWS).Copy
After:=activeWB.Sheets(activeWB.Sheets.count)
assuming that oWS is the index of the worksheet you want to copy.
Sub Add_Bridge_1()
Dim wbk1 As Workbook, wbk2 As Workbook
'add your own file path
fileStr = "C:\Program Files\Microsoft Office\Office\HL DDS Templates.xlsx"
Set wbk1 = ActiveWorkbook
Set wbk2 = Workbooks.Add(fileStr)
'wbk2.Sheets("Bridge 1").Copy After:=Workbooks("WorkbookNameYouCopyCodeInto").Sheets(1)
wbk2.Sheets("Sheet Name").Copy After:=wbk1.Sheets(1)
wbk2.Saved = True
End Sub

Resources