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
Related
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
I am trying to copy values from 30 books of excel to another book excel , but I am not sure how to reference the 30 books because they have different name.Also I don't know how to reference the file of excel that I want to close.
I am running the macro from the book of excel that it will have all the values from the other excels.
My problems are:
Don't know how to reference the Excel worbooks that will open because they have different names.
How to paste the values with offset.
I have this code:
Sub MacroPrueba4()
'Paso 1: Declarar las variables
Dim Archivos As String
Dim vals As Variant
Worksheets("Hoja1").Range("A3:A7").Copy
vals = Worksheets("Hoja1").Range("A2:F14").Value
Archivos = Dir("C:\Users\fernandofernandez\Desktop\Prueba\*.xlsx")
Do While Archivos <> “”
'Paso 3: Open the books one by one
Workbooks.Open "C:\Users\fernandofernandez\Desktop\Prueba\" & Archivos
'code
vals = Worksheets(1).Range("E2").Value
' this is something i use to paste the format of the last column format
Workbooks("libro2").Range("C10").End(xlToRight).Select
Selection.EntireColumn.Select
Selection.Copy
ActiveSheet.Range("C10").End(xlToRight).Offset(0, 1).Select
Selection.EntireColumn.Select
ActiveSheet.Paste
'Selection.Paste
' this is where I will paste de value
' is this right??
ActiveSheet.Range("C10").End(xlToRight).Offset(0, 1).Select
Selection.Value = vals
'this close the active excel, but I think it would close the excel that I am pasting the values, because it would be the activeworkbook. I want to close only the 30 excels that will open in the loop.
ActiveWorkbook.Close SaveChanges:=True
Archivos = Dir
Loop
End Sub
The function Workbooks.Open returns the workbook open, so you can write :
my_workbook = Workbooks.Open "C:\Users\fernandofernandez\Desktop\Prueba\" & Archivos
' Your code
my_workbook.Close SaveChanges:=True
With this you are sure that you close the right book.
For assign values don't use select if you want a clean code.
You can do :
ActiveSheet.Range("C10").End(xlToRight).Offset(0, 1).value = vals
You're welcome.
Merge data from all workbooks in a folder.
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
See the link below for all details.
https://www.rondebruin.nl/win/s3/win008.htm
You may want ton consider this utility as well.
https://www.rondebruin.nl/win/addins/rdbmerge.htm
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
I've multiple files and with data sample
All files seems the same as the file in the image
This is my master file structure
this my code so for
Sub Append()
'Append data from other files
Path = "E:\NPM PahseIII\"
Dim c As Range
'find the second empty cell in ColA
Set c = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Offset(2, 0)
Filename = Dir(Path & "*.xlsx")
Do While Filename <> ""
If InStr(Filename, ".") > 0 Then
Filenamenoext = Left(Filename, InStr(Filename, ".") - 1)
End If
c.Value = Filenamenoext
Set c = c.Offset(1, 0)
Workbooks.Open Filename:=Path & Filename, ReadOnly:=True
ThisWorkbook.Activate
ActiveSheet.Range("B3:E6").Select
Selection.Consolidate Sources:=Array("'" & Path & "[" & Filename &
"]Sheet1'!B3:B6")
Workbooks(Filename).Close
Filename = Dir()
Loop
End Sub
After running this code my master file become this
As from the second image we can see that only the file names are written in the master file but data is not consolidated from other files, I stuck in this issue for a full day and don't know what's wrong with my code,
Secondly i want that there should be no repeat if i run this code again then the data should not need to be duplicated is currently it's duplicating data because when i run the code again the file names are written again starting at the bottom of the previous record.
what could be the issue with my current code in order to consolidate data from other files and don't do duplication?
Try this and see how you get along.
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
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.