How to pull data from multiple workbooks in a folder? - excel

I have hundreds of Excel (Microsoft® Excel® for Microsoft 365 MSO (16.0.14326.20702) 32-bit ) files in a folder which have one sheet in common.
For example- Let's consider the sheet as "data".
I want to pull specific cells (C2:C15) out of each of them and transpose them into a separate "masterfile".
This code runs unsuccessfully.
Sub ExtractData()
Dim masterfile As Workbook
Dim wb As Workbook
Dim directory As String
Dim fileName As String
Dim NextRow As Long
Application.DisplayAlerts = False
Application.ScreenUpdating = False
Set masterfile = ThisWorkbook
directory = masterfile.Worksheets("Sheet1").Range("E1")
fileName = Dir(directory & "*.xl??")
Do While fileName <> ""
If fileName <> ThisWorkbook.Name Then
Set wb = Workbooks.Open(directory & fileName)
wb.Worksheets("data").Range("C2:C15").Copy
masterfile.Activate
NextRow = Cells(Rows.Count, "C").End(xlUp).Row + 1
Worksheets("Sheet1").Range("C" & NextRow).Select
Selection.PasteSpecial Paste:=xlPasteAll, Operation:=xlNone, SkipBlanks:=False, Transpose:=True
wb.Close savechanges:=False
End If
fileName = Dir
Loop
Application.DisplayAlerts = True
Application.ScreenUpdating = True
MsgBox "Data has been Compiled, Please Check!"
End Sub

Some suggestions:
Sub ExtractData()
Dim masterSheet As Worksheet
Dim wb As Workbook
Dim directory As String
Dim fileName As String, cDest As Range
Application.DisplayAlerts = False
Application.ScreenUpdating = False
Set masterSheet = ThisWorkbook.Worksheets("Sheet1")
directory = masterSheet.Range("E1").Value
'### ensure trailing path separator ###
If Right(directory, 1) <> "\" Then directory = directory & "\"
'first paste location
Set cDest = masterSheet.Cells(masterSheet.Rows.Count, "C").End(xlUp).Offset(1)
fileName = Dir(directory & "*.xl??")
Do While fileName <> ""
If fileName <> ThisWorkbook.Name Then
Set wb = Workbooks.Open(directory & fileName)
wb.Worksheets("data").Range("C2:C15").Copy
cDest.PasteSpecial Paste:=xlPasteAll, Operation:=xlNone, _
SkipBlanks:=False, Transpose:=True
Set cDest = cDest.Offset(1) 'next paste row
wb.Close savechanges:=False
End If
fileName = Dir
Loop
Application.DisplayAlerts = True
Application.ScreenUpdating = True
MsgBox "Data has been Compiled, Please Check!"
End Sub

Related

Saving excel files to network drive takes too long using VBA

I have a macro which loops through excel files in a network drive path and performs few operations on the pivots and then tries to save the file in the same network path.
It works fine for the first 5 - 10 files and then it randomly stops saving the files.
The progress bar in the save box does not go any further.
Unable to save image
I have included the VBA code below
Sub CLEAR_ADI_PIVOT_DT_SRC()
Dim myPath As String
Dim myExtension As String
Dim myFile As String
Dim wb As Workbook
Dim ws As Worksheet
Dim FilePath As String
Dim PriorQuarter As String
Dim PrevQtrSheet As String
Dim filestr1 As String
Dim PrevQuarter As String
PrevQtrSheet = "Rebates Template " & Range("B2").Value
PrevQuarter = Range("B2").Value
PriorQuarter = Range("A2").Value
myPath = Range("I2").Value & "ADI\"
If Right(myPath, 1) <> "\" Then
myPath = myPath & "\"
End If
On Error GoTo ErrHandler
'Optimize Macro Speed
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
'Target File Extension (must include wildcard "*")
myExtension = "*.xl*"
'Target Path with Ending Extension
myFile = Dir(myPath & myExtension)
'Loop through each Excel file in folder
Do While myFile <> ""
'Set variable equal to opened workbook
Application.DisplayAlerts = False
Debug.Print myPath & myFile
Set wb = Workbooks.Open(filename:=myPath & myFile, UpdateLinks:=False)
wb.Worksheets("ADI").Visible = True
wb.Worksheets("ADI").Activate
Cells.Find(What:="totals:", After:=ActiveCell, LookIn:=xlFormulas, _
LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False).Activate
ActiveCell.Offset(-1, 0).Select
Dim AdiClearRange As Range
Set AdiClearRange = Range("AE" & ActiveCell.Row, "C14")
AdiClearRange.Select
Selection.ClearContents
Range("B15").Select
'Insert rows in ADI sheet
Dim x As Long
For x = 1 To 500
Range("B19:AE19").Select
Selection.Copy
Selection.Insert Shift:=xlDown
Range("B14").Select
Application.CutCopyMode = False
Next x
'Delete prior quarter template sheet
For Each Sheet In wb.Worksheets
If Sheet.Name = "Rebates Template " & PriorQuarter Then
Sheet.Delete
End If
Next Sheet
'change data source of previous quarter pivots
'Get range of the previous template
wb.Worksheets(PrevQtrSheet).Activate
Range("AH5").Select
If ActiveSheet.AutoFilterMode Then ActiveSheet.AutoFilter.ShowAllData
ActiveSheet.Range("$A$5:$KD$683").AutoFilter Field:=34, Criteria1:="<>"
'ActiveSheet.Range("$A$5:$KD$683").AutoFilter Field:=34, Criteria1:="<>0"
Range("AH5").Select
Selection.End(xlDown).Select
'Change range of pivot 1 and pivot 7 and apply previous quarter filter in pivots
Dim rng As Range
Dim SourceAddress As String
Set rng = Range("A5", "AH" & ActiveCell.Row)
SourceAddress = "'" & PrevQtrSheet & "'" & "!" & "$A$5:" & ActiveCell.Address(RowAbsolute:=True, ColumnAbsolute:=True)
Debug.Print SourceAddress
Sheets("Check").Select
Dim myPivotField As PivotField
Dim filterValue As String
ActiveSheet.PivotTables("PivotTable3").ChangePivotCache wb.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=SourceAddress)
ActiveSheet.PivotTables("PivotTable3").RefreshTable
ActiveSheet.Range("P1").Value = PrevQuarter
wb.Close SaveChanges:=True
'Get next file name
myFile = Dir
Loop
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
ResetSettings:
'Reset Macro Optimization Settings
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
ErrHandler:
'MsgBox Err.Description, vbExclamation
'Resume ResetSettings
End Sub

Excel VBA to export data from table to text file using another field as the file name

I've got an Excel report with a table and I need to export a single column from that table to a txt file. I'm calculating the file name that I want to use for the txt file based on fields in the spreadsheet so I want to use that field as my file name.
The data I want to export is in column S.
The file name I want to use is in cell E5 and contains the file extension of txt as well.
This is what I have so far:
Sub FileNameAsCellContent()
Dim FileName As String
Dim Path As String
Application.DisplayAlerts = False
Path = "C:\temp\"
FileName = Range("E5").Value & ".txt"
ActiveWorkbook.SaveAs Path & FileName, xlTextWindows
Application.DisplayAlerts = True
MsgBox "Export Complete. Click OK to continue"
End Sub
This works but it's exporting the entire worksheet and I only need one column out of the table.
This sub will save the data in Sheet1, column S to a text file.
Sub FileNameAsCellContent()
Dim wsSource As Worksheet
Dim fileName As String
Dim wsDest As Worksheet
Dim wbDest As Workbook
Set wsWource = Worksheets("Sheet1")
fileName = "C:\temp\" & wsSource.Cells("E5").Value & ".txt"
' Create a new worksheet.
Set wsDest = Worksheets.Add
' Copy data from column S to new worksheet
wsSource.Range("S:S").Copy
wsDest.Range("A:A").PasteSpecial xlPasteValues
' Worksheet.Move with no arguments will
' copy the worksheet to a new workbook
' and remove it from the current workbook.
wsDest.Move
' Grab a reference to the new workbook.
With Workbooks
Set wbDest = .Item(.Count)
End With
' Save new workbook as text file & close.
Application.DisplayAlerts = False
wbDest.SaveAs fileName, xlTextWindows
wbDest.Close False
Application.DisplayAlerts = True
End Sub
Export Column to Textfile
Sub FileNameAsCellContent()
Dim Path As String
Dim FileName As String
Path = "C:\temp\"
FileName = Range("E5").Value & ".txt"
Application.ScreenUpdating = False
Columns("S").Copy
With Workbooks.Add
.Worksheets(1).Columns("A").PasteSpecial
Application.DisplayAlerts = False
.SaveAs Path & FileName, xlTextWindows
.Close False
Application.DisplayAlerts = True
End With
Application.ScreenUpdating = True
MsgBox "Export Complete. Click OK to continue"
End Sub
Using a TextStream Object
Option Explicit
Sub Export()
Const SHT_NAME = "Customer_Class_Clean-Up_Report"
Const RNG_NAME = "H7" ' cell
Const TABLENAME = "Table_Query_from_CHECKMATE"
Const COL = "Yard,AccountNum,CustomerCategory"
Const FOLDER = "C:\temp\"
Dim ws As Worksheet, rng As Range, cell As Range
Dim filename As String, n As Long
Dim FSO As Object, ts As Object
Set FSO = CreateObject("Scripting.FileSystemObject")
' build export filename
Set ws = ThisWorkbook.Sheets(SHT_NAME)
filename = FOLDER & ws.Range(RNG_NAME).Value
If Len(filename) = 0 Then
MsgBox "Filename is blank", vbCritical
Exit Sub
End If
filename = filename & ".txt"
' create text file
Set ts = FSO.createTextfile(filename, True, True) 'overwrite, unicode
Set rng = ws.Range(TABLENAME & "[[#Headers],[" & COL & "]]")
For Each cell In ws.Range(rng, rng.End(xlDown))
ts.writeline cell
n = n + 1
Next
' finish
ts.Close
MsgBox n & " Rows exported from " & rng.Address & vbCrLf & _
" to " & filename, vbInformation, "Click OK to continue."
End Sub
I used the following and it will work for what I need. It's copying the table content that I need, pasting it in a sheet called "ForExport" and then saving the content in that worksheet with the file name I need.
Sub Export()
Application.ScreenUpdating = False
Sheets("ForExport").Visible = True
Sheets("ForExport").Select
Columns("A:A").Select
Selection.Delete Shift:=xlToLeft
Sheets("Customer_Class_Clean-Up_Report").Select
Range( _
"Table_Query_from_CHECKMATE[[#Headers],[Yard,AccountNum,CustomerCategory]]"). _
Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
Sheets("ForExport").Select
Range("A1").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Range("A1").Select
Sheets("ForExport").Select
Dim FileName As String
Dim Path As String
Sheets("Customer_Class_Clean-Up_Report").Select
Path = "C:\temp\"
FileName = Range("H7").Value & ".txt"
Sheets("ForExport").Select
ActiveWorkbook.SaveAs Path & FileName, xlTextPrinter
'ActiveWorkbook.Close SaveChanges:=True
Sheets("Customer_Class_Clean-Up_Report").Select
Range("B5").Select
MsgBox "Export complete. File is located in the C:\temp directory. Click OK to continue."
End Sub

Consolidate Worksheet from a Folder and Append by Column

I have to compile all the worksheets in a folder and append it by column (in addition to labelling the file name).
All of the worksheets are expected to have the following dimensions.
I am expected to provide the following outcome (to be able to merge the file name is a bonus):
Sub macro1()
'Define variables
Dim wbk As Workbook
Dim Filename As String
Dim Path As String
i = 3
ThisWorkbook.Activate
'Location of individual templates
Path = "filename\"
Filename = Dir(Path & "*.xlsx")
'Prevents screen from flickering when Macro is running
Application.ScreenUpdating = False
'Start of loop
Do While Len(Filename) > 0
'Opens excel file
Set wbk = Workbooks.Open(Path & Filename)
'Copies the file names
Sheets("1.Consol").Select
Range("C3:E3").Select
ActiveCell.Value = Replace(Filename, ".xlsx", "")
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues
'Labelling low
Range("C4").Select
ActiveCell.Value = "Low"
Range("C4").Select
Selection.Copy
Selection.PasteSpecial xlPasteValues
'Labelling Medium
Range("D4").Select
ActiveCell.Value = "Medium"
Range("D4").Select
Selection.Copy
Selection.PasteSpecial xlPasteValues
'Labelling High
Range("E4").Select
ActiveCell.Value = "High"
Range("E4").Select
Selection.Copy
Selection.PasteSpecial xlPasteValues
'Copies the whole range of data
Range("C3:E100").Copy
'Change to the sheet name you want to paste to
ThisWorkbook.Activate
Sheets("1.Consol").Select
Cells(3, i).Select
ActiveSheet.Paste
Selection.EntireColumn.ColumnWidth = 10
Selection.EntireRow.AutoFit
i = i + 3
Application.DisplayAlerts = False
wbk.Saved = True
wbk.Close True
Filename = Dir
Loop
End Sub
Based on this set up (see the location of data)
Source files:
Consolidated file:
Step through the code pressing F8 key
Read code's comments and adjust it to fit your needs
Public Sub OpenFilesAndCopyContents()
' Basic error handling
On Error GoTo CleanFail
' Turn off stuff
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
ThisWorkbook.UpdateLinks = xlUpdateLinksNever
' Define files path
Dim filesPath As String
filesPath = "C:\Temp\Test\"
' Define and set target sheet
Dim targetSheet As Worksheet
Set targetSheet = ThisWorkbook.Worksheets("1.Consol")
' Define initial cell in target sheet
Dim targetRange As Range
Set targetRange = targetSheet.Range("B1")
' Define file name string to match
Dim fileString As String
fileString = "samplefile"
' Define file name
Dim fileName As String
fileName = Dir(filesPath, vbNormal)
' Start a counter for worksheets
Dim sheetCounter As Long
' Loop through files
Do While fileName <> ""
'Set variable equal to opened workbook
If InStr(LCase(fileName), LCase(fileString)) > 0 Then
' Set a reference to the workbook
Dim sourceWorkbook As Workbook
Set sourceWorkbook = Workbooks.Open(fileName:=filesPath & fileName, UpdateLinks:=False)
'Ensure Workbook has opened before moving on to next line of code
DoEvents
' Loop through sheets in workbook
Dim sourceSheet As Worksheet
For Each sourceSheet In sourceWorkbook.Worksheets
' Add workbook and worksheet as title
targetRange.Offset(0, sheetCounter).Value = sourceWorkbook.Name & " " & sourceSheet.Name
' Copy paste values from worksheet
sourceSheet.Range("B1:D8").Copy targetRange.Offset(1, sheetCounter)
sheetCounter = sheetCounter + 3
Next sourceSheet
'Close Workbook without saving
sourceWorkbook.Close SaveChanges:=False
'Ensure Workbook has closed before moving on to next line of code
DoEvents
End If
fileName = Dir()
Loop
CleanExit:
' Turn on stuff
Application.ScreenUpdating = True
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
ThisWorkbook.UpdateLinks = xlUpdateLinksAlways
Exit Sub
CleanFail:
MsgBox "Error " & Err.Description
GoTo CleanExit
End Sub
Let me know if it works

Copying a range from all files within a folder and pasting into master workbook

I'm fairly new to VBA so I apologize ahead of time. I've been getting involved with some complex operations and I would greatly appreciate some help or input.
With this macro, I am trying to:
Copy a specific range (2 column widths) from a specific sheet that is within all files in a given folder.
Paste the range values (and formatting if possible) in a column on the already open master workbook starting at B7 and moving over 2 columns for every new document so that the pasted data does not overlap.
Close files after copy/paste complete
As of right now I receive a
Run-time Error 9: Subscript out of range
for
Workbooks("RF_Summary_Template").Worksheets("Summary").Select
I know this is the least of my problems, though.
Below is my code:
Sub compile()
Dim SummaryFile As String, SummarySheet As String, summaryColumn As Long
Dim GetDir As String, Path As String
Dim dataFile As String, dataSheet As String, LastDataRow As Long
Dim i As Integer, FirstDataRow As Long
'********************************
RF_Summary_Template = ActiveWorkbook.Name 'summarybook
Summary = ActiveSheet.Name 'summarysheet
summaryColumn = Workbooks(RF_Summary_Template).Sheets(Summary).Cells(Columns.Count, 1).End(xlToLeft).Column + 1
CreateObject("WScript.Shell").Popup "First, browse to the correct directory, select ANY file in the directory, and click Open.", 2, "Select Install Base File"
GetDir = Application.GetOpenFilename("Excel Files (*.xls*), *.xls*")
If GetDir <> "False" Then
Path = CurDir & "\"
Else
MsgBox "Directory not selected"
Exit Sub
End If
Application.ScreenUpdating = False
dataFile = Dir(Path & "*.xls")
While dataFile <> ""
Workbooks.Open (dataFile)
Worksheets("Dashboard").Activate
ActiveSheet.Range("AY17:AZ35").Copy
Workbooks("RF_Summary_Template").Worksheets("Summary").Select
Range("B8").PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
Workbooks(dataFile).Close
summaryColumn = summaryColumn + 2
dataFile = Dir()
Wend
Workbooks(RF_Summary_Template).Save
Application.ScreenUpdating = True
End Sub
Thanks a million
I hope this helps. Run the procedure "CopyDataBetweenWorkBooks"
Sub CopyDataBetweenWorkbooks()
Dim wbSource As Workbook
Dim shTarget As Worksheet
Dim shSource As Worksheet
Dim strFilePath As String
Dim strPath As String
' Initialize some variables and
' get the folder path that has the files
Set shTarget = ThisWorkbook.Sheets("Summary")
strPath = GetPath
' Make sure a folder was picked.
If Not strPath = vbNullString Then
' Get all the files from the folder
strfile = Dir$(strPath & "*.xls", vbNormal)
Do While Not strfile = vbNullString
' Open the file and get the source sheet
Set wbSource = Workbooks.Open(strPath & strfile)
Set shSource = wbSource.Sheets("Dashboard")
'Copy the data
Call CopyData(shSource, shTarget)
'Close the workbook and move to the next file.
wbSource.Close False
strfile = Dir$()
Loop
End If
End Sub
' Procedure to copy the data.
Sub CopyData(ByRef shSource As Worksheet, shTarget As Worksheet)
Const strRANGE_ADDRESS As String = "AY17:AZ35"
Dim lCol As Long
'Determine the last column.
lCol = shTarget.Cells(8, shTarget.Columns.Count).End(xlToLeft).Column + 1
'Copy the data.
shSource.Range(strRANGE_ADDRESS).Copy
shTarget.Cells(8, lCol).PasteSpecial xlPasteValuesAndNumberFormats
' Reset the clipboard.
Application.CutCopyMode = xlCopy
End Sub
' Fucntion to get the folder path
Function GetPath() As String
With Application.FileDialog(msoFileDialogFolderPicker)
.ButtonName = "Select a folder"
.Title = "Folder Picker"
.AllowMultiSelect = False
'Get the folder if the user does not hot cancel
If .Show Then GetPath = .SelectedItems(1) & "\"
End With
End Function
I hope this helps :)
With the help of this code you can copy all workbooks and worksheets data
into one workbook
Sub copydata()
Dim fso As Scripting.FileSystemObject
Dim fill As Scripting.File
Dim oldfolder As String
Dim newfolder As String
Dim subfolder As Folder
Dim myfolder As Folder
Dim fd As FileDialog
Dim loopcount As Integer
Dim wb
Dim wb2 As Workbook
Dim rr As Range
Set fso = New Scripting.FileSystemObject
Set wb = ThisWorkbook
Set fd = Application.FileDialog(msoFileDialogFolderPicker)
fd.Title = "Please Select Folder to copy"
fd.ButtonName = "Go!"
fd.Show
oldfolder = fd.SelectedItems(1)
Set myfolder = fso.GetFolder(oldfolder)
'Application.ScreenUpdating = False
Application.EnableEvents = False
For Each subfolder In myfolder.SubFolders
For Each fill In subfolder.Files
If fill Like "*.xlsm" Or fill Like "*.xlsx" Or fill Like ".*xls" Then
'fill.Range("A1:Z100").Copy
Set wb2 = Application.Workbooks.Open(fill,0 , True)
wb2.Activate
For loopcount = 1 To wb2.Worksheets.Count
wb2.Activate
Worksheets(loopcount).Activate
Range("A1:Z300").Copy 'Replace your range
wb.Activate
Sheet1.Activate
Set rr = Range("A:A").Find("", Range("A1"))
rr.Select
ActiveSheet.Paste
ActiveCell.Offset(1, 0).Select
Next loopcount
wb2.Close False
End If
Application.CutCopyMode = False
Debug.Print fill.Name
Next fill
Next subfolder
MsgBox "Done"
For Each fill In myfolder.Files
Application.DisplayAlerts = False
If fill Like "*.xlsm" Or fill Like "*.xlsx" Or fill Like ".*xls" Or fill Like "*.xlsb" Then
'fill.Range("A1:Z100").Copy
Set wb2 = Application.Workbooks.Open(fill, 0, True)
wb2.Activate
For loopcount = 1 To wb2.Worksheets.Count
wb2.Activate
Worksheets(loopcount).Activate
Range("A:Z").EntireColumn.Hidden = False
Range("A1:Z1").AutoFilter
Range("A1:Z300").Copy
wb.Activate
Sheet1.Activate
Set rr = Range("A:A").Find("", Range("A1"))
rr.Select
ActiveSheet.Paste
ActiveCell.Offset(1, 0).Select
Next loopcount
wb2.Close False
End If
Application.CutCopyMode = False
Debug.Print fill.Name
Next fill
Application.EnableEvents = True
End Sub
Sub fdsdf()
'template is in the f_path
'files are under fpath\Raw Data\Ban
f_path = tree
Set wbTemplate = Workbooks.Open(Filename:=f_path & "\DEMAND_Template.xlsx")
MyFolder = f_path & "\Raw Data\Ban"
MyFile = Dir(MyFolder & "\*.xlsx")
Do While MyFile <> ""
Set wbIB = Workbooks.Open(Filename:=MyFolder & "\" & MyFile)
wbIB.Activate
Sheets("Sheet1").Select
r_cnt = ActiveSheet.UsedRange.Rows.Count
ran1 = "12:" & r_cnt
Rows(ran1).Select
Selection.Copy
wbTemplate.Select
Sheets("Sheet1").Select
r_cnt1 = ActiveSheet.UsedRange.Rows.Count
ran2 = Sheets("Sheet1").Range("A1048576").End(xlUp).Row + 1
Range("A" & ran2).Select
ActiveSheet.Paste
Application.CutCopyMode = False
wbIB.Close False
MyFile = Dir
Loop
wbTemplate.Save
End Sub
Sub final_consolidate()
f_path = "tree"
strFileToOpenIB = Application.GetOpenFilename(Title:="Please select the Consolidated file for Bangladesh", FileFilter:="Excel Files *.xlsx* (*.xlsx*),")
Set wbIB = Workbooks.Open(strFileToOpenIB)
wbIB.Activate
Sheets("Sheet1").Select
Sheets("Sheet1").Copy
wbIB.Activate
Sheets("Sheet2").Select
Sheets("Sheet2").Copy After:=Workbooks("Book1").Sheets(1)
wbIB.Activate
ActiveWorkbook.Close
Windows("Book1").Activate
strFileToOpenIB = Application.GetOpenFilename(Title:="Please select the Consolidated file for SriLanka", FileFilter:="Excel Files *.xlsx* (*.xlsx*),")
Set wbIB = Workbooks.Open(strFileToOpenIB)
wbIB.Activate
Sheets("Sheet1").Select
Sheets("Sheet1").Copy After:=Workbooks("Book1").Sheets(2)
wbIB.Activate
Sheets("Sheet2").Select
Sheets("Sheet2").Copy After:=Workbooks("Book1").Sheets(3)
wbIB.Activate
ActiveWorkbook.Close
Windows("Book1").Activate
ActiveWorkbook.SaveAs Filename:=f_path, FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
End Sub

Loop to populate Excel from other excel sheets

I have 1 Master Excel Workbook that I need to populate from other excel files.... Basically Open 1 by 1 each file from One folder and copy paste on the Master Workbook... I wrote One macro.. but it still have some flows... I don't know how to make it work
Option Explicit
Sub fill()
Dim wb As Workbook, wb2 As Workbook, mywb As Workbook
Dim sPath As String, sFilename As String
Dim NbRows As Integer, rg As Range
Set wb = ThisWorkbook
'Application.ScreenUpdating = False
Set mywb = Workbooks("C:\Users\cbensoussan.FGC\Desktop\MASTER FOLDER.xlsx")
sPath = "F:\Blotters\OPT\2014\Jan\"
sFilename = Dir(sPath & "*.xls*")
Do While Len(sFilename) > 0
Set wb2 = Workbooks.Open(sPath & sFilename)
Range("A2:AO2").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
mywb.Select
Range("A2").Select
Range(Selection, Selection.End(xlDown) + 1).Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
wb2.Close False
sFilename = Dir
Loop
Application.ScreenUpdating = True
End Sub
Thank you for your help
Something like this (untested)
Option Explicit
Sub fill()
Dim wb As Workbook, wb2 As Workbook, mywb As Workbook
Dim sPath As String, sFilename As String
Dim NbRows As Integer, rg As Range, rgCopy as range
Set wb = ThisWorkbook
'Application.ScreenUpdating = False
'if not already open:
Set mywb = Workbooks.Open("C:\Users\cbensoussan.FGC\Desktop\MASTER FOLDER.xlsx")
'or if already open:
'Set mywb = Workbooks("MASTER FOLDER.xlsx")
sPath = "F:\Blotters\OPT\2014\Jan\"
sFilename = Dir(sPath & "*.xls*")
Do While Len(sFilename) > 0
Set wb2 = Workbooks.Open(sPath & sFilename)
with wb2.Activesheet
Set rgCopy = .Range("A2:AO" & .cells(.rows.count, 1).End(xlUp).Row)
end with
mywb.activesheet.cells(rows.count, 1).end(xlUp). _
Resize(rgCopy.Rows.Count, rgCopy.Columns.Count).Value = rgCopy.Value
wb2.Close False
sFilename = Dir
Loop
Application.ScreenUpdating = True
End Sub

Resources