Grabbing data from all sheets in given directory - excel

I am trying to create a macro that will grab information from all sheets in all workbook(s) located in a specific directory. I am a VBA newbie, so I'm basically limited to what I can copy or modify with extremely limited programming knowledge. I have been trying to modify the macro I got off a website below.
How would I modify the SearchValue line to filter any date in general? Would I have to create a new variable? Also, how would modify the ShName line to scan every single sheet in the workbooks?
Sub ConsolidateErrors()
Dim MyPath As String, FilesInPath As String
Dim MyFiles() As String
Dim SourceRcount As Long, FNum As Long
Dim mybook As Workbook, BaseWks As Worksheet
Dim sourceRange As Range, destrange As Range
Dim rnum As Long, CalcMode As Long
Dim rng As Range, SearchValue As String
Dim FilterField As Integer, RangeAddress As String
Dim ShName As Variant, RwCount As Long
MyPath = "C:\Documents and Settings\user\Desktop\New Folder"
ShName = 1
RangeAddress = Range("A1:N" & Rows.Count).Address
FilterField = 1
SearchValue = "10/21/2010"
If Right(MyPath, 1) <> "\" Then
MyPath = MyPath & "\"
End If
FilesInPath = Dir(MyPath & "*.xl*")
If FilesInPath = "" Then
MsgBox "No files found"
Exit Sub
End If
FNum = 0
Do While FilesInPath <> ""
FNum = FNum + 1
ReDim Preserve MyFiles(1 To FNum)
MyFiles(FNum) = FilesInPath
FilesInPath = Dir()
Loop
With Application
CalcMode = .Calculation
.Calculation = xlCalculationManual
.ScreenUpdating = False
.EnableEvents = False
End With
Set BaseWks = Workbooks.Add(xlWBATWorksheet).Worksheets(1)
rnum = 1
If FNum > 0 Then
For FNum = LBound(MyFiles) To UBound(MyFiles)
Set mybook = Nothing
On Error Resume Next
Set mybook = Workbooks.Open(MyPath & MyFiles(FNum))
On Error GoTo 0
If Not mybook Is Nothing Then
On Error Resume Next
With mybook.Worksheets(ShName)
Set sourceRange = .Range(RangeAddress)
End With
If Err.Number > 0 Then
Err.Clear
Set sourceRange = Nothing
End If
On Error GoTo 0
If Not sourceRange Is Nothing Then
rnum = RDB_Last(1, BaseWks.Cells) + 1
With sourceRange.Parent
Set rng = Nothing
.AutoFilterMode = False
sourceRange.AutoFilter Field:=FilterField, _
Criteria1:=SearchValue
With .AutoFilter.Range
RwCount = .Columns(1).Cells. _
SpecialCells(xlCellTypeVisible).Cells.Count - 1
If RwCount = 0 Then
Else
Set rng = .Resize(.Rows.Count - 1, .Columns.Count). _
Offset(1, 0).SpecialCells(xlCellTypeVisible)
If rnum + RwCount < BaseWks.Rows.Count Then
rng.Copy BaseWks.Cells(rnum, "A")
End If
End If
End With
.AutoFilterMode = False
End With
End If
mybook.Close savechanges:=False
End If
Next FNum
BaseWks.Columns.AutoFit
MsgBox "Look at the merge results in the new workbook after you click on OK"
End If
With Application
.ScreenUpdating = True
.EnableEvents = True
.Calculation = CalcMode
End With
End Sub

You can use the InputBox() method to grab data from the user when the code is run. Here is a simple example:
Option Explicit
Sub test()
Dim SearchValue As String
SearchValue = InputBox("Enter Date", "Date, please")
If (SearchValue = "") Then Exit Sub ' case when "Cancel" or nothing is entered
If (IsDate(SearchValue) = False) Then
MsgBox "Sorry, that is not a valid date."
Exit Sub
End If
' Do other stuff
End Sub
Here is some documentation from Microsoft:
http://msdn.microsoft.com/en-us/library/office/aa195768(v=office.11).aspx

To answer the 2nd question you had Also, how would modify the ShName line to scan every single sheet in the workbooks?
Try this syntax ...
Dim wks as Worksheet
For each wks in myBook.Worksheets
'run code here
Next
Your above code will need a bit of tweaking to make sure it's referencing the right sheet each time and such, but that wks variable will help tremendously.

Related

Copy and Paste Data from Multiple Excel Files within the same folder into one Single Excel File

Good morning!
I'm trying to loop through Excel Files within the same folder to copy and paste a range of data into a single Excel Workbook.
The start location of the cell range is always consistent, it starts at Cell D12 and ends anywhere between C91 and Z91.The table dimensions however do vary from 80 R x 2 C to 80 R x 22 C. The Excel files I'm trying to pull the Data from have multiples sheets but the sheet where I need the Data from always has the same name, in this case its "Performance".
I need it to
Find the data dimension in file (table)
Copy that table
Paste to destination (below previous table)
Loop through to next file
Repeat Step 1-4
Thanks a lot for any help, I appreciate any help, let me know if you have any specific questions.
SO isn't a code writing service, but yesterday I did something similar, that you can use for a starting point.
Code is in one workbook. It creates a new workbook (Target) and loops the folder for all worksbooks (Source) and copies the worksheets from these to the target.
Finally, saves the Target:
Option Explicit
Public Function ImportSheets()
Dim Source As Excel.Workbook
Dim Target As Excel.Workbook
Const FolderName As String = "C:\Path\SomeFolder"
Const FileMask As String = "*.xlsx"
Const Separator As String = "\"
Const TargetMask As String = "Current Projects {0}.xlsx"
Dim Worksheet As Excel.Worksheet
Dim FileName As String
Dim Count As Integer
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Set Target = Workbooks.Add
FileName = Dir(FolderName & Separator & FileMask)
Do While FileName <> ""
Set Source = Workbooks.Open(FolderName & Separator & FileName)
For Each Worksheet In Source.Worksheets
Count = Target.Worksheets.Count
Source.Worksheets(Worksheet.Name).Copy After:=Target.Worksheets(Count)
Next
Source.Close False
FileName = Dir()
Loop
Set Source = Nothing
Target.Worksheets(1).Delete
FileName = Replace(TargetMask, "{0}", Format(Date, "yyyy-mm-dd"))
Target.SaveAs FolderName & Separator & FileName
Target.Close
Set Target = Nothing
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Function
You should be able to expand it a bit to only copy a specific part of the source worksheets.
Maybe this?
Sub Basic_Example_1()
Dim MyPath As String, FilesInPath As String
Dim MyFiles() As String
Dim SourceRcount As Long, Fnum As Long
Dim mybook As Workbook, BaseWks As Worksheet
Dim sourceRange As Range, destrange As Range
Dim rnum As Long, CalcMode As Long
'Fill in the path\folder where the files are
MyPath = "C:\Users\Ron\test"
'Add a slash at the end if the user forget it
If Right(MyPath, 1) <> "\" Then
MyPath = MyPath & "\"
End If
'If there are no Excel files in the folder exit the sub
FilesInPath = Dir(MyPath & "*.xl*")
If FilesInPath = "" Then
MsgBox "No files found"
Exit Sub
End If
'Fill the array(myFiles)with the list of Excel files in the folder
Fnum = 0
Do While FilesInPath <> ""
Fnum = Fnum + 1
ReDim Preserve MyFiles(1 To Fnum)
MyFiles(Fnum) = FilesInPath
FilesInPath = Dir()
Loop
'Change ScreenUpdating, Calculation and EnableEvents
With Application
CalcMode = .Calculation
.Calculation = xlCalculationManual
.ScreenUpdating = False
.EnableEvents = False
End With
'Add a new workbook with one sheet
Set BaseWks = Workbooks.Add(xlWBATWorksheet).Worksheets(1)
rnum = 1
'Loop through all files in the array(myFiles)
If Fnum > 0 Then
For Fnum = LBound(MyFiles) To UBound(MyFiles)
Set mybook = Nothing
On Error Resume Next
Set mybook = Workbooks.Open(MyPath & MyFiles(Fnum))
On Error GoTo 0
If Not mybook Is Nothing Then
On Error Resume Next
With mybook.Worksheets(1)
Set sourceRange = .Range("A1:C1")
End With
If Err.Number > 0 Then
Err.Clear
Set sourceRange = Nothing
Else
'if SourceRange use all columns then skip this file
If sourceRange.Columns.Count >= BaseWks.Columns.Count Then
Set sourceRange = Nothing
End If
End If
On Error GoTo 0
If Not sourceRange Is Nothing Then
SourceRcount = sourceRange.Rows.Count
If rnum + SourceRcount >= BaseWks.Rows.Count Then
MsgBox "Sorry there are not enough rows in the sheet"
BaseWks.Columns.AutoFit
mybook.Close savechanges:=False
GoTo ExitTheSub
Else
'Copy the file name in column A
With sourceRange
BaseWks.cells(rnum, "A"). _
Resize(.Rows.Count).Value = MyFiles(Fnum)
End With
'Set the destrange
Set destrange = BaseWks.Range("B" & rnum)
'we copy the values from the sourceRange to the destrange
With sourceRange
Set destrange = destrange. _
Resize(.Rows.Count, .Columns.Count)
End With
destrange.Value = sourceRange.Value
rnum = rnum + SourceRcount
End If
End If
mybook.Close savechanges:=False
End If
Next Fnum
BaseWks.Columns.AutoFit
End If
ExitTheSub:
'Restore ScreenUpdating, Calculation and EnableEvents
With Application
.ScreenUpdating = True
.EnableEvents = True
.Calculation = CalcMode
End With
End Sub
You can find other similar examples in the link below.
https://www.rondebruin.nl/win/s3/win008.htm

Copy multiple workbooks and paste in a single sheet

I have multiple workbooks with same columns and I need to consolidate it to one single sheet with the column names to be copied only once.
Couldn't find a comprehensive solution. Please hep.
Try the below, you will have to adjust this to your needs.
in nutshell, you need the below steps
Get the folder location you have the sheets
get xl files that you are interested , with a specific name etc
for each of these files, and for each sheet in these files
3a. copy the cells to the last filled row
3b. paste in the target, from the first empty row.
Test
Option Explicit
Sub LoopAllExcelflesInFolder()
Dim wb As Workbook
Dim target As Worksheet
Dim flePath As String
Dim fle As String
Dim fleDlg As fleDialog
Dim ws As Worksheet
Dim firstEmptyRowTarget As Long
Dim lastRowSource As Long
Dim RangeToMove As Range
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
'get folder loc from the user
Set fleDlg = Application.fleDialog(msofleDialogFolderPicker)
With fleDlg
.Title = "Select A Target Folder"
.AllowMultiSelect = False
If .Show <> -1 Then GoTo nxt 'in case cancelled get to next block
flePath = .SelectedItems(1) & "\"
End With
nxt:
flePath = flePath
If flePath = "" Then GoTo closeandgo
Set target = ActiveWorkbook.Sheets("Sheet1") 'change your target here
fle = Dir(flePath & "*.xls*")
LRDest = 1 '(assuming starting row is 1)
Do While fle <> ""
Set wb = Workbooks.Open(flename:=flePath & fle)
'' for each worsheet , copy the contents / include your logic here if the sheet has a specific name/pattern etc. assuming the column headers are the same
For Each ws In wb.Sheets
lastRowSource = ws.Cells(ws.Rows.Count, 1).End(xlUp).Row ' find the last row in the source
Set RangeToMove = ws.Range("A1:AJ" & LRSrc) 'Change the columns you want to copy here
RangeToMove.Copy target.Cells(firstEmptyRowTarget, 1)
firstEmptyRowTarget = target.Cells(target.Rows.Count, 1).End(xlUp).Row + 1 ''Save the last row in the target after copyin
Next
DoEvents
'Get next fle name
fle = Dir
Loop
MsgBox "done..."
closeandgo:
'Reset Macro Optimization Settings
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
End Sub
I see these types of questions come up every once in a while. There are a few ways you could go with this. Try the code below, and see how you get along. Post back if you have additional questions.
Sub Basic_Example_1()
Dim MyPath As String, FilesInPath As String
Dim MyFiles() As String
Dim SourceRcount As Long, Fnum As Long
Dim mybook As Workbook, BaseWks As Worksheet
Dim sourceRange As Range, destrange As Range
Dim rnum As Long, CalcMode As Long
'Fill in the path\folder where the files are
MyPath = "C:\Users\Ron\test"
'Add a slash at the end if the user forget it
If Right(MyPath, 1) <> "\" Then
MyPath = MyPath & "\"
End If
'If there are no Excel files in the folder exit the sub
FilesInPath = Dir(MyPath & "*.xl*")
If FilesInPath = "" Then
MsgBox "No files found"
Exit Sub
End If
'Fill the array(myFiles)with the list of Excel files in the folder
Fnum = 0
Do While FilesInPath <> ""
Fnum = Fnum + 1
ReDim Preserve MyFiles(1 To Fnum)
MyFiles(Fnum) = FilesInPath
FilesInPath = Dir()
Loop
'Change ScreenUpdating, Calculation and EnableEvents
With Application
CalcMode = .Calculation
.Calculation = xlCalculationManual
.ScreenUpdating = False
.EnableEvents = False
End With
'Add a new workbook with one sheet
Set BaseWks = Workbooks.Add(xlWBATWorksheet).Worksheets(1)
rnum = 1
'Loop through all files in the array(myFiles)
If Fnum > 0 Then
For Fnum = LBound(MyFiles) To UBound(MyFiles)
Set mybook = Nothing
On Error Resume Next
Set mybook = Workbooks.Open(MyPath & MyFiles(Fnum))
On Error GoTo 0
If Not mybook Is Nothing Then
On Error Resume Next
With mybook.Worksheets(1)
Set sourceRange = .Range("A1:C1")
End With
If Err.Number > 0 Then
Err.Clear
Set sourceRange = Nothing
Else
'if SourceRange use all columns then skip this file
If sourceRange.Columns.Count >= BaseWks.Columns.Count Then
Set sourceRange = Nothing
End If
End If
On Error GoTo 0
If Not sourceRange Is Nothing Then
SourceRcount = sourceRange.Rows.Count
If rnum + SourceRcount >= BaseWks.Rows.Count Then
MsgBox "Sorry there are not enough rows in the sheet"
BaseWks.Columns.AutoFit
mybook.Close savechanges:=False
GoTo ExitTheSub
Else
'Copy the file name in column A
With sourceRange
BaseWks.cells(rnum, "A"). _
Resize(.Rows.Count).Value = MyFiles(Fnum)
End With
'Set the destrange
Set destrange = BaseWks.Range("B" & rnum)
'we copy the values from the sourceRange to the destrange
With sourceRange
Set destrange = destrange. _
Resize(.Rows.Count, .Columns.Count)
End With
destrange.Value = sourceRange.Value
rnum = rnum + SourceRcount
End If
End If
mybook.Close savechanges:=False
End If
Next Fnum
BaseWks.Columns.AutoFit
End If
ExitTheSub:
'Restore ScreenUpdating, Calculation and EnableEvents
With Application
.ScreenUpdating = True
.EnableEvents = True
.Calculation = CalcMode
End With
End Sub
https://www.rondebruin.nl/win/s3/win008.htm

How To Merge different workbooks with same structure in to one using dynamic Range

I have multiple work books with one sheet each all with the same structure would like to merge these in to one workbook found some examples on the net but been unable to achieve what I want this code I have will create the merge but it only picks one column. I would like to copy the entire used range starting from a point eg "A2" have tried a couple here is what I tried the commented lines are what I have tried and did not work any suggestions welcome please
Sub Trymerge()
Dim FolderPath As String, Path As String, count As Integer
Dim ThisWB As String, lngFilecounter As Long
Dim wbDest As Workbook, shtDest As Worksheet, ws As Worksheet
Dim Filename As String, Wkb As Workbook
Dim CopyRng As Range, Dest As Range
Dim RowofCopySheet As Integer
ThisWB = ActiveWorkbook.Name
FolderPath = "H:\Staging\Testmerge"
' path = FolderPath & "\*.xls*"
'Filename = Dir(path)
Filename = Dir(FolderPath & "\*.xls*", vbNormal)
MsgBox Filename
RowofCopySheet = 11
Application.EnableEvents = False
Application.ScreenUpdating = False
Set shtDest = ActiveWorkbook.Sheets(1)
Do While Filename <> ""
MsgBox Filename
count = count + 1
If Not Filename = ThisWB Then
Set Wkb = Workbooks.Open(Filename:=FolderPath & "\" & Filename)
MsgBox "working file" & Filename
Set CopyRng = Wkb.Sheets(1).Range(Cells(RowofCopySheet, 1), Cells(Cells(Rows.count, 1).End(xlUp).Row, Cells(1, Columns.count).End(xlToLeft).Column))
'Wkb.Sheets(1).Range("A11").Select
' Set CopyRng = Wkb.Sheets(1).Range(RowofCopySheet, ActiveCell.End(xlDown).End(xlToRight))
'Set CopyRng = Wkb.Sheets(1).Range(Cells(RowofCopySheet, 1), Cells(.UsedRange.Rows.count, .UsedRange.Columns.count))
Set Dest = shtDest.Range("A" & shtDest.Cells(Rows.count, 1).End(xlUp).Row + 1)
CopyRng.Copy
Dest.PasteSpecial xlPasteFormats
Dest.PasteSpecial xlPasteValuesAndNumberFormats
Application.CutCopyMode = False 'Clear Clipboard
Wkb.Close False
End If
Filename = Dir()
Loop
' Range("Q8").Value = count
MsgBox count & " : files found in folder"
End Sub
This is the script that I use to loop through a folder, copy data out of all files, and then save that data into a combined spreadsheet located elsewhere. You'll need to change myPath to the path to your file folder, change the i variable to the range you need, and the j variable to the location/range of your combined spreadsheet.
Sub CombineReports()
Dim wb As Workbook
Dim myPath As String
Dim myFile As String
Dim i As Long
Dim j As Long
'Optimize Macro Speed
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
Application.CutCopyMode = False
'Target Folder Path For Macro
myPath = "I:\Pricing\mt access\Tier Reports\Final Reports\"
'In Case of Cancel
myPath = myPath
If myPath = "" Then GoTo ResetSettings
'Loop through each Excel file in folder
myFile = Dir(myPath)
Do While myFile <> ""
'Set variable equal to opened workbook
Set wb = Workbooks.Open(Filename:=myPath & myFile)
DoEvents
'Count rows in your spreadsheet and set range to copy
i = wb.Worksheets(1).Range("A" & Rows.Count).End(xlUp).Row
wb.Worksheets(1).Range("A5", "N" & i).Copy
'Combine data from each spreadsheet into one main sheet
With Workbooks.Open("I:\Pricing\mt access\Tier Reports\Final Reports\Combined Report\CombinedTierReport.xlsx")
DoEvents
j = Workbooks("CombinedTierReport.xlsx").Worksheets("AllStores").Range("B" & Rows.Count).End(xlUp).Row
Workbooks("CombinedTierReport.xlsx").Worksheets("AllStores").Range("A" & j + 1).PasteSpecial xlPasteValues
Workbooks("CombinedTierReport.xlsx").Save
Workbooks("CombinedTierReport.xlsx").Close
End With
DoEvents
'Save and Close Workbook
Application.DisplayAlerts = False
wb.Close SaveChanges:=False
Application.DisplayAlerts = True
DoEvents
'Get next file name
myFile = Dir
Loop
'Reset Macro Optimization Settings
ResetSettings:
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
Application.CutCopyMode = True
End Sub
If your code is already working you can just change your code as below:
Code you have:
Set CopyRng = Wkb.Sheets(1).Range(Cells(RowofCopySheet, 1), Cells(Cells(Rows.count, 1).End(xlUp).Row, Cells(1, Columns.count).End(xlToLeft).Column))
You can make it slightly more simple by changing your copyrange:
Assuming the Column A goes to the bottom of your sheet and Assuming the first Row goes to the last Column of your sheet
Dim LastRow As Long
Dim LastCol As Long
LastRow = Range("A" & Rows.Count).End(xlUp).Row
LastCol = Cells(1, Columns.Count).End(xlToLeft).Column
Set CopyRng = Wkb.Sheets(1).Range(Cells(RowofCopySheet, 1), Cells(LastRow, LastCol))
With this the CopyRng will take your whole Range and not only the last column.
You can easily merge data from all workbooks in a folder (below each other).
Sub Basic_Example_1()
Dim MyPath As String, FilesInPath As String
Dim MyFiles() As String
Dim SourceRcount As Long, Fnum As Long
Dim mybook As Workbook, BaseWks As Worksheet
Dim sourceRange As Range, destrange As Range
Dim rnum As Long, CalcMode As Long
'Fill in the path\folder where the files are
MyPath = "C:\Users\Ron\test"
'Add a slash at the end if the user forget it
If Right(MyPath, 1) <> "\" Then
MyPath = MyPath & "\"
End If
'If there are no Excel files in the folder exit the sub
FilesInPath = Dir(MyPath & "*.xl*")
If FilesInPath = "" Then
MsgBox "No files found"
Exit Sub
End If
'Fill the array(myFiles)with the list of Excel files in the folder
Fnum = 0
Do While FilesInPath <> ""
Fnum = Fnum + 1
ReDim Preserve MyFiles(1 To Fnum)
MyFiles(Fnum) = FilesInPath
FilesInPath = Dir()
Loop
'Change ScreenUpdating, Calculation and EnableEvents
With Application
CalcMode = .Calculation
.Calculation = xlCalculationManual
.ScreenUpdating = False
.EnableEvents = False
End With
'Add a new workbook with one sheet
Set BaseWks = Workbooks.Add(xlWBATWorksheet).Worksheets(1)
rnum = 1
'Loop through all files in the array(myFiles)
If Fnum > 0 Then
For Fnum = LBound(MyFiles) To UBound(MyFiles)
Set mybook = Nothing
On Error Resume Next
Set mybook = Workbooks.Open(MyPath & MyFiles(Fnum))
On Error GoTo 0
If Not mybook Is Nothing Then
On Error Resume Next
With mybook.Worksheets(1)
Set sourceRange = .Range("A1:C1")
End With
If Err.Number > 0 Then
Err.Clear
Set sourceRange = Nothing
Else
'if SourceRange use all columns then skip this file
If sourceRange.Columns.Count >= BaseWks.Columns.Count Then
Set sourceRange = Nothing
End If
End If
On Error GoTo 0
If Not sourceRange Is Nothing Then
SourceRcount = sourceRange.Rows.Count
If rnum + SourceRcount >= BaseWks.Rows.Count Then
MsgBox "Sorry there are not enough rows in the sheet"
BaseWks.Columns.AutoFit
mybook.Close savechanges:=False
GoTo ExitTheSub
Else
'Copy the file name in column A
With sourceRange
BaseWks.cells(rnum, "A"). _
Resize(.Rows.Count).Value = MyFiles(Fnum)
End With
'Set the destrange
Set destrange = BaseWks.Range("B" & rnum)
'we copy the values from the sourceRange to the destrange
With sourceRange
Set destrange = destrange. _
Resize(.Rows.Count, .Columns.Count)
End With
destrange.Value = sourceRange.Value
rnum = rnum + SourceRcount
End If
End If
mybook.Close savechanges:=False
End If
Next Fnum
BaseWks.Columns.AutoFit
End If
ExitTheSub:
'Restore ScreenUpdating, Calculation and EnableEvents
With Application
.ScreenUpdating = True
.EnableEvents = True
.Calculation = CalcMode
End With
End Sub
If, for some reason, you wanted to do the merge and have the data sets arranged horizontally, instead of vertically, you could use the script below.
Sub Basic_Example_3()
Dim MyPath As String, FilesInPath As String
Dim MyFiles() As String
Dim SourceCcount As Long, Fnum As Long
Dim mybook As Workbook, BaseWks As Worksheet
Dim sourceRange As Range, destrange As Range
Dim Cnum As Long, CalcMode As Long
'Fill in the path\folder where the files are
MyPath = "C:\Users\Ron\test"
'Add a slash at the end if the user forget it
If Right(MyPath, 1) <> "\" Then
MyPath = MyPath & "\"
End If
'If there are no Excel files in the folder exit the sub
FilesInPath = Dir(MyPath & "*.xl*")
If FilesInPath = "" Then
MsgBox "No files found"
Exit Sub
End If
'Fill the array(myFiles)with the list of Excel files in the folder
Fnum = 0
Do While FilesInPath <> ""
Fnum = Fnum + 1
ReDim Preserve MyFiles(1 To Fnum)
MyFiles(Fnum) = FilesInPath
FilesInPath = Dir()
Loop
'Change ScreenUpdating, Calculation and EnableEvents
With Application
CalcMode = .Calculation
.Calculation = xlCalculationManual
.ScreenUpdating = False
.EnableEvents = False
End With
'Add a new workbook with one sheet
Set BaseWks = Workbooks.Add(xlWBATWorksheet).Worksheets(1)
Cnum = 1
'Loop through all files in the array(myFiles)
If Fnum > 0 Then
For Fnum = LBound(MyFiles) To UBound(MyFiles)
Set mybook = Nothing
On Error Resume Next
Set mybook = Workbooks.Open(MyPath & MyFiles(Fnum))
On Error GoTo 0
If Not mybook Is Nothing Then
On Error Resume Next
Set sourceRange = mybook.Worksheets(1).Range("A1:A10")
If Err.Number > 0 Then
Err.Clear
Set sourceRange = Nothing
Else
'if SourceRange use all rows then skip this file
If sourceRange.Rows.Count >= BaseWks.Rows.Count Then
Set sourceRange = Nothing
End If
End If
On Error GoTo 0
If Not sourceRange Is Nothing Then
SourceCcount = sourceRange.Columns.Count
If Cnum + SourceCcount >= BaseWks.Columns.Count Then
MsgBox "Sorry there are not enough columns in the sheet"
BaseWks.Columns.AutoFit
mybook.Close savechanges:=False
GoTo ExitTheSub
Else
'Copy the file name in the first row
With sourceRange
BaseWks.cells(1, Cnum). _
Resize(, .Columns.Count).Value = MyFiles(Fnum)
End With
'Set the destrange
Set destrange = BaseWks.cells(2, Cnum)
'we copy the values from the sourceRange to the destrange
With sourceRange
Set destrange = destrange. _
Resize(.Rows.Count, .Columns.Count)
End With
destrange.Value = sourceRange.Value
Cnum = Cnum + SourceCcount
End If
End If
mybook.Close savechanges:=False
End If
Next Fnum
BaseWks.Columns.AutoFit
End If
ExitTheSub:
'Restore ScreenUpdating, Calculation and EnableEvents
With Application
.ScreenUpdating = True
.EnableEvents = True
.Calculation = CalcMode
End With
End Sub

Exclude Empty Rows & Retain Destination Formatting while Merging Multiple Workbooks

I customized Merging multiple Sheets of Data code from this site. I achieve a result with critical issues.
Empty Rows from the defined Range are being copied too. Tried avoiding them by tweaking RDB_Last function.
Unable to retain the Destination Formatting. Trying to use If PasteAsValues = True Then.
Below is the Code
Sub MergeAllWorkbooks()
Dim FirstCell As String
Dim MyPath As String, FilesInPath As String
Dim myFiles() As String
Dim SourceRcount As Long, FNum As Long
Dim mybook As Workbook, BaseWks As Worksheet
Dim sourceRange As Range, destrange As Range
Dim rnum As Long, CalcMode As Long
' Change this to the path\folder location of your files.
MyPath = "C:\Users\zatin.dharmapuri\Desktop\3. 2018\Raw Data Month wise\Jan-2018"
' Add a slash at the end of the path if needed.
If Right(MyPath, 1) <> "\" Then
MyPath = MyPath & "\"
End If
' If there are no Excel files in the folder, exit.
FilesInPath = Dir(MyPath & "*.xl*")
If FilesInPath = "" Then
MsgBox "No files found"
Exit Sub
End If
' Fill the myFiles array with the list of Excel files
' in the search folder.
FNum = 0
Do While FilesInPath <> ""
FNum = FNum + 1
ReDim Preserve myFiles(1 To FNum)
myFiles(FNum) = FilesInPath
FilesInPath = Dir()
Loop
' Set various application properties.
With Application
CalcMode = .Calculation
.Calculation = xlCalculationManual
.ScreenUpdating = False
.EnableEvents = False
End With
' Set the sheet name for the data to be copied to.
Set BaseWks = ThisWorkbook.Sheets("Sheet3")
rnum = 1
' Loop through all files in the myFiles array.
If FNum > 0 Then
For FNum = LBound(myFiles) To UBound(myFiles)
Set mybook = Nothing
On Error Resume Next
Set mybook = Workbooks.Open(MyPath & myFiles(FNum))
On Error GoTo 0
If Not mybook Is Nothing Then
On Error Resume Next
'Change this range to fit your own needs.
With mybook.Worksheets("Defect Analysis Reports")
Set sourceRange = .Range("A5:J104")
End With
'FirstCell = "A5"
'Set sourceRange = .Range(FirstCell & ":" & RDB_Last(1, .Row))
' Test if the row of the last cell is equal to or greater than the row of the first cell.
'If RDB_Last(1, .Row) < .Range(FirstCell).Row Then
' Set sourceRange = Nothing
' End If
'End With
If Err.Number > 0 Then
Err.Clear
Set sourceRange = Nothing
Else
' If source range uses all columns then
' skip this file.
If sourceRange.Columns.Count >= BaseWks.Columns.Count Then
Set sourceRange = Nothing
End If
End If
On Error GoTo 0
If Not sourceRange Is Nothing Then
SourceRcount = sourceRange.Rows.Count
If rnum + SourceRcount >= BaseWks.Rows.Count Then
MsgBox "There are not enough rows in the target worksheet."
BaseWks.Columns.AutoFit
mybook.Close savechanges:=False
GoTo ExitTheSub
Else
' Copy the file name in column A.
With sourceRange
BaseWks.Cells(rnum, "A"). _
Resize(.Rows.Count).Value = myFiles(FNum)
End With
' Set the destination range.
Set destrange = BaseWks.Range("B" & rnum)
' Copy the values from the source range
' to the destination range.
With Sourcesheet.Range("A5:J104").Value =
DestinationSheet.Range("A5:J104").Value
End With
destrange.Value = sourceRange.Value
rnum = rnum + SourceRcount
End If
End If
mybook.Close savechanges:=False
End If
Next FNum
BaseWks.Columns.AutoFit
End If
ExitTheSub:
' Restore the application properties.
With Application
.ScreenUpdating = True
.EnableEvents = True
.Calculation = CalcMode
End With
MsgBox "All Data has been merged successfully"
End Sub
I'm a beginner in VBA.

How to select columns based on header in excel vba project

I am currently working on an Excel VBA project which merges data from multiple workbooks.
The workbooks are identical in terms of columns but have variable row lengths.
I would like to only extract data from Columns with the header "School Name", "Participants" and "Status". These are the cells B2, G2 and H2. Thus, effectively, I only want the data from columns B, G and H.
Currently, I extract data using a set range (B3:H80) and then delete the unwanted columns. How do I edit the source range to .usedrange and edit that accordingly?
I have attached the code below. Thanks for your help!
Private Sub MergeAllWorkbooks()
Dim MyPath As String, FilesInPath As String
Dim MyFiles() As String
Dim SourceRcount As Long, FNum As Long
Dim mybook As Workbook, BaseWks As Worksheet
Dim sourceRange As Range, destrange As Range
Dim rnum As Long, CalcMode As Long
' Change this to the path\folder location of your files.
MyPath = "C:\Users\" & Environ("username") & "\Dropbox\Folder1\"
' Add a slash at the end of the path if needed.
If Right(MyPath, 1) <> "\" Then
MyPath = MyPath & "\"
End If
' If there are no Excel files in the folder, exit.
FilesInPath = Dir(MyPath & "*.xl*")
If FilesInPath = "" Then
MsgBox "No files found"
Exit Sub
End If
' Fill the myFiles array with the list of Excel files
' in the search folder.
FNum = 0
Do While FilesInPath <> ""
FNum = FNum + 1
ReDim Preserve MyFiles(1 To FNum)
MyFiles(FNum) = FilesInPath
FilesInPath = Dir()
Loop
' Set various application properties.
With Application
CalcMode = .Calculation
.Calculation = xlCalculationManual
.ScreenUpdating = False
.EnableEvents = False
End With
' Add a new workbook with one sheet.
Set BaseWks = Workbooks.Add(xlWBATWorksheet).Worksheets(1)
rnum = 1
' Loop through all files in the myFiles array.
If FNum > 0 Then
For FNum = LBound(MyFiles) To UBound(MyFiles)
Set mybook = Nothing
On Error Resume Next
Set mybook = Workbooks.Open(MyPath & MyFiles(FNum))
On Error GoTo 0
If Not mybook Is Nothing Then
On Error Resume Next
' Change this range to fit your own needs.
With mybook.Worksheets(1)
Set sourceRange = .Range("B3:H80")
End With
If Err.Number > 0 Then
Err.Clear
Set sourceRange = Nothing
Else
' If source range uses all columns then
' skip this file.
If sourceRange.Columns.Count >= BaseWks.Columns.Count Then
Set sourceRange = Nothing
End If
End If
On Error GoTo 0
If Not sourceRange Is Nothing Then
SourceRcount = sourceRange.Rows.Count
If rnum + SourceRcount >= BaseWks.Rows.Count Then
MsgBox "There are not enough rows in the target worksheet."
BaseWks.Columns.AutoFit
mybook.Close savechanges:=False
GoTo ExitTheSub
Else
' Copy the file name in column C.
With sourceRange
BaseWks.Cells(rnum, "C"). _
Resize(.Rows.Count).Value = MyFiles(FNum)
End With
' Set the destination range.
Set destrange = BaseWks.Range("B" & rnum)
' Copy the values from the source range
' to the destination range.
With sourceRange
Set destrange = destrange. _
Resize(.Rows.Count, .Columns.Count)
End With
destrange.Value = sourceRange.Value
rnum = rnum + SourceRcount
End If
End If
mybook.Close savechanges:=False
End If
Next FNum
BaseWks.Columns.AutoFit
End If
ExitTheSub:
' Restore the application properties.
With Application
.ScreenUpdating = True
.EnableEvents = True
.Calculation = CalcMode
End With
Columns("C:F").Delete
End Sub
Change
destrange.Value = SourceRange.Value
To
destrange.Columns(1).Value = SourceRange.Columns(1).Value
destrange.Columns(2).Value = SourceRange.Columns(6).Value
destrange.Columns(3).Value = SourceRange.Columns(7).Value

Resources