I've been trying to scavange together a macro which will merge several .CSV files.
However, the data I need in said file (GPS data) is located in different rows of column A. I therefor need it to search for part of a string, in this case there are a few strings related to GPS, but I only need GPS latitud and longitude (which will always be found one after another).
Any help is appreciated! The code might look a bit.. like shit, ive been trying to mess with it to make it work together!
Sub MergeAllWorkbooks()
Dim SummarySheet As Worksheet
Dim FolderPath As String
Dim directory As Object
Dim NRow As Long
Dim FileName As String
Dim WorkBk As Workbook
Dim SourceRange As Range
Dim DestRange As Range
Dim S_Lat, S_Long, D_Lat, D_Long As Range
Dim i As Integer
Dim icount As Integer
Dim icount2 As Integer
Application.ScreenUpdating = False
Application.DisplayAlerts = False
With Application.FileDialog(msoFileDialogFolderPicker)
.AllowMultiSelect = False
If .Show = -1 Then '-1 = yes or true
FolderPath = .SelectedItems(1) & "\"
Else
MsgBox "FilePath not selected!", , "Path selecter"
Exit Sub
End If
End With
' Create a new workbook and set a variable to the first sheet.
Set SummarySheet = Workbooks.Add(xlWBATWorksheet).Worksheets(1)
' NRow keeps track of where to insert new rows in the destination workbook.
NRow = 2
' Call Dir the first time, pointing it to all .csv files in the folder path.
FileName = dir(FolderPath & "*.csv")
SummarySheet.Range("A1") = "Filnamn"
SummarySheet.Range("B1") = "Latitud"
SummarySheet.Range("C1") = "Longitud"
' Loop until Dir returns an empty string.
Do While FileName <> ""
' Open a workbook in the folder
Set WorkBk = Workbooks.Open(FolderPath & "\" & FileName)
' Set the cell in column A to be the file name.
SummarySheet.Range("A" & NRow).Value = FileName
' Set the source range to be A9 through C9.
' Modify this range for your workbooks.
' It can span multiple rows.
For i = 1 To 200
If InStr(1, LCase(Range("A" & i)), "GPS Latitude") <> 0 Then 'If GPS appears in the string then
icount = i
icount2 = icount + 1
Set S_Lat = WorkBk.Worksheets(1).Range("A" & icount) ' Set the S_Lat variable
Set S_Long = WorkBk.Worksheets(1).Range("A" & icount2) ' Set the S_Long variable
Exit For
End If
Next i
' Set the destination range to start at column B and
' be the same size as the source range.
' SummarySheet.Range("B" & NRow).Value = S_Lat.Value ***** Didnt work? ******
' SummarySheet.Range("C" & NRow).Value = S_Long.Value ***** Didnt work? ******
Set D_Lat = SummarySheet.Range("B" & NRow)
Set D_Long = SummarySheet.Range("C" & NRow)
' Copy over the values from the source to the destination.
D_Lat.Value = S_Lat.Value
D_Long.Value = S_Long.Value
' Increase NRow so that we know where to copy data next.
NRow = NRow + D_Lat.Rows.Count
' Close the source workbook without saving changes.
WorkBk.Close savechanges:=False
' Use Dir to get the next file name.
FileName = dir()
Loop
' Call AutoFit on the destination sheet so that all
' data is readable.
' SummarySheet.Columns.AutoFit
End Sub
This simple code is not giving you a complete working macro, it will Look for "Latitude" in column A and when found it will transfer the cel.value, and the cel.value below it, to two rows side-by-side in column B and column C on the same worksheet. You will need to wrap it inside your Workbooks.Open loop, modify the Range in the source worksheet to include a last row, include a last row for your new workbook's worksheet and add it to the code inside the If statement. Try to work this into your code and when you encounter problems, you can return to SO and ask a specific question concerning your macro. The macro was tested with actual longitudes and latitudes, in column A, an placed in columns B and C side-by-side.
Dim lRow As Long
lRow = Sheet1.Cells(Rows.Count, 1).End(xlUp).Row
For Each cel In Range("A1:A38")
If InStr(1, cel.Value, "Latitude") Then
x = x + 1
Cells(x, 2).Value = cel.Value
Cells(x, 3).Value = cel.Offset(1).Value
End If
Next cel
Related
HiHi,
disclaimer: I have no experience with coding
I have a code which takes values from cells (B2:C2) from multiple worksheets in a folder on my desktop and pasts it into the master workbook. This works great, however, I don't want the copied cells pasted consecutively down cells (F3:G3)- they need to be pasted into specific cells. This sounds complicated, and I'm sure it is. First, here's my base code which I have modified (from this code) to fit my needs:
Sub MergeAllWorkbooks()
Dim SummarySheet As Worksheet
Dim FolderPath As String
Dim FileName As String
Dim WorkBk As Workbook
Dim SourceRange As Range
Dim DestRange As Range
'Optimize Macro Speed
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
' Set summarysheet to activeworkbook/activesheet where the macro runs
Set SummarySheet = ActiveWorkbook.ActiveSheet
' Modify this folder path to point to the files you want to use.
FolderPath = "C:\Users\Me\Desktop\Extracted Data\16.12.2021\"
' Call Dir the first time, pointing it to all Excel files in the folder path.
FileName = Dir(FolderPath & "*.csv*")
' Loop until Dir returns an empty string.
Do While FileName <> ""
' Open a workbook in the folder
Set WorkBk = Workbooks.Open(FolderPath & FileName)
'loop through all Sheets in WorkBk
For Each sh In WorkBk.Worksheets
' Set the source range to be A9 through C9.
Set SourceRange = Sheets(sh.Name).Range("B2:C2")
' Set the destination range to start at column B and
' be the same size as the source range.
Set DestRange = SummarySheet.Range("F" & SummarySheet.Range("F" & Rows.Count).End(xlUp).Row + 1)
Set DestRange = DestRange.Resize(SourceRange.Rows.Count, _
SourceRange.Columns.Count)
' Copy over the values from the source to the destination.
DestRange.Value = SourceRange.Value
Next sh
' Close the source workbook without saving changes.
WorkBk.Close savechanges:=False
' Use Dir to get the next file name.
FileName = Dir()
Loop
' Call AutoFit on the destination sheet so that all
' data is readable.
ActiveSheet.Columns.AutoFit
'Message Box when tasks are completed
MsgBox "Task Complete!"
End Sub
So, this runs and does copy the values from each workbook within the source folder to the master. I want to make it so that:
If it copies from a work book that contains i.e "282579" and "Ch.4" to the cells that correspond to those values. To clarify, I have added a Screenshot of my master workbook.
If it copies a value from a source workbook with a title that contains 282579 and Ch.4, it will paste those 2 values into 282579's Ch.4 cell located at (F10:G10) and so on.
Tried using the If function (like, If (workbook has this in its name) but I have no idea how to specify which cells it needs to be pasted in)
I hope I have made sense and that this is understandable.
edit: if a copy of the data I use is needed, I can supply it
Use a Regular Expression to extract the SN and Ch. numbers from the filename. Use Find to located the SN on the summary sheet then scan the merged rows for the Ch number.
Sub MergeAllWorkbooks()
' Modify this folder path to point to the files you want to use.
Const FolderPath = "C:\Users\Me\Desktop\Extracted Data\16.12.2021\"
Dim wb As Workbook, wbCSV As Workbook
Dim ws As Worksheet, wsCSV As Worksheet
Dim rngCSV As Range, fnd As Range, bFound As Boolean
Dim Filename As String, n As Long, i As Long
' Set summarysheet to activeworkbook/activesheet where the macro runs
Set wb = ActiveWorkbook
Set ws = wb.ActiveSheet
' regular expression to extract numbers
' example VS SAAV_282579 ch 4 Data.csv
Dim Regex As Object, m As Object, SN As Long, CH As Long
Set Regex = CreateObject("vbscript.regexp")
With Regex
.IgnoreCase = True
.Pattern = "(_(\d+) +ch +(\d+) +Data)"
End With
' Call Dir the first time, pointing it to all Excel files in the folder path.
Filename = Dir(FolderPath & "*Data.csv*")
' Loop until Dir returns an empty string.
Application.ScreenUpdating = False
Do While Filename <> ""
' extract SN and Ch from filename
If Regex.test(Filename) Then
Set m = Regex.Execute(Filename)(0).submatches
SN = m(1)
CH = m(2)
Debug.Print Filename, SN, CH
' Find SN
Set fnd = ws.Range("B:B").Find(SN, LookIn:=xlValues, lookat:=xlWhole)
If fnd Is Nothing Then
MsgBox SN & " not found !", vbCritical, Filename
Else
' find ch.
bFound = False
For i = 0 To fnd.MergeArea.Count - 1
If ws.Cells(fnd.Row + i, "D") = CH Then ' Col D
bFound = True
' Open a workbook in the folder
Set wbCSV = Workbooks.Open(FolderPath & Filename, ReadOnly:=True)
ws.Cells(fnd.Row + i, "F").Resize(, 2).Value2 = wbCSV.Sheets(1).Range("B2:C2").Value2
' Close the source workbook without saving changes.
wbCSV.Close savechanges:=False
Exit For
End If
Next
If bFound = False Then
MsgBox "Ch." & CH & " not found for " & SN, vbExclamation, Filename
End If
End If
n = n + 1
Else
Debug.Print Filename & " skipped"
End If
' Use Dir to get the next file name.
Filename = Dir()
Loop
' Call AutoFit on the destination sheet so that all
' data is readable.
ws.Columns.AutoFit
Application.ScreenUpdating = True
'Message Box when tasks are completed
MsgBox n & " csv files found.", vbInformation, "Task Complete!"
End Sub
From your explanation it is not clear if you are able to match the source worksheets with a specific Ch. If you can, I'd advise to define a Ch variable soon after the For each sh loop, then you need to initiate another loop in the master workbook on column D for each row until you get the row number of the Ch variable. You use the row number to define the destination range
Dim SummarySheet As Worksheet
Dim FolderPath As String
Dim FileName As String
Dim WorkBk As Workbook
Dim SourceRange As Range
Dim DestRange As Range
Dim n As Long 'Ch substring position
Dim Ch As String 'Ch variable for source file
Dim LastChRow As Long 'lastrow of Ch in summary sheet
Dim ChSummary As String 'Define the Ch string in summary sheet
'Optimize Macro Speed
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
' Set summarysheet to activeworkbook/activesheet where the macro runs
Set SummarySheet = ActiveWorkbook.ActiveSheet
' Define LastChRow
LastChRow = SummarySheet.Cells(Rows.Count, "D").End(xlUp).Row
' Modify this folder path to point to the files you want to use.
FolderPath = "C:\Users\Me\Desktop\Extracted
Data\16.12.2021\"
' Call Dir the first time, pointing it to all Excel files in the
folder path.
FileName = Dir(FolderPath & "*.csv*")
' Loop until Dir returns an empty string.
Do While FileName <> ""
'define starting charachter of Ch source file for string manipulation
n = InStr(FileName, "Ch")
'define Ch variable
Ch = Trim(Mid(FileName, n, 5))
' Open a workbook in the folder
Set WorkBk = Workbooks.Open(FolderPath & FileName)
'loop through all Sheets in WorkBk
For Each sh In WorkBk.Worksheets
For i = 3 To LastChRow
'Define ChSummary variable in loop
ChSummary = "Ch" & " " & SummarySheet.Range("D" & i)
If ChSummary = Ch Then
' Set the source range to be A9 through C9.
Set SourceRange = Sheets(sh.Name).Range("B2:C2")
' Set the destination range to start at column B and
' be the same size as the source range.
Set DestRange = SummarySheet.Range("F" & i & ":G" & i)
'Set DestRange = DestRange.Resize(SourceRange.Rows.Count, _
' SourceRange.Columns.Count)
' Copy over the values from the source to the destination.
DestRange.Value = SourceRange.Value
End If
Next i
Next sh
' Close the source workbook without saving changes.
WorkBk.Close savechanges:=False
' Use Dir to get the next file name.
FileName = Dir()'
I'm trying to add "#" in each cell in the first column since Row7 until the cell is blank. And I have several files in one folder which needs to repeat. Is it possible to do this by VBA? It always shown, there's something wrong with the code. Many thanks for help.
Sub LoopAllFilesInAFolder()
'Loop through all files in a folder
Dim fileName As Variant
fileName = Dir("C:\Users)
While fileName <> ""
'Insert the actions to be performed on each file
Dim last As Long
Dim i As Long
'Find the last row with values in Column A
last = .Cells(.Rows.Count, 1).End(xlUp).Row
'Loop from the 7th row to the last row.
For i = 7 To last
'Assign the value
Cells(i, 1).Value = "#" & Cells(i, 1).Value
Next i
'This example will print the file name to the immediate window
Debug.Print fileName
'Set the fileName to the next file
fileName = Dir
Wend
End Sub
Please, try the next adapted code:
Sub LoopAllFilesInAFolder()
Dim folderName As String, fileName As String, wb As Workbook
Dim ws As Worksheet, last As Long, i As Long, arr
folderName = "C:\Users\Lin.Yu\Desktop\NewFolder\" 'take care to the ending backslash
fileName = Dir(folderName & "*.xlsx")
While fileName <> ""
Set wb = Workbooks.Open(folderName & fileName)
Set ws = wb.Sheets(1) 'use here the appropriate sheet, if not the first one
With ws
'Find the last row with values in Column A
last = .cells(.rows.count, 1).End(xlUp).row
arr = .Range("A1:A" & last).value 'put the column in an array to make the code faster
'Loop from the 7th array row to the last row and process.
For i = 7 To UBound(arr)
arr(i, 1) = "#" & arr(i, 1)
Next i
.Range("A1:A" & last).value = arr 'drop the processed array content
End With
wb.Close True 'save and close the processed workbook
'Set the fileName to the next file
fileName = Dir
Wend
End Sub
Edited:
Please, test the next compact variant, using Evaluate instead of iteration:
Sub LoopAllFilesInAFolder()
Dim folderName As String, fileName As String, wb As Workbook
Dim ws As Worksheet, last As Long, i As Long, rng As Range
folderName = ThisWorkbook.path & "\" ' "C:\Users\Lin.Yu\Desktop\NewFolder\"
fileName = Dir(folderName & "*.xlsx")
While fileName <> ""
Set wb = Workbooks.Open(folderName & fileName)
Set ws = wb.Sheets(1) 'use here the appropriate sheet, if not the first one
With ws
'Find the last row with values in Column A
last = .cells(.rows.count, 1).End(xlUp).row
Set rng = .Range("A7:A" & last)
rng.value = Evaluate("""#""&" & rng.Address)
End With
wb.Close True 'save and close the processed workbook
'Set the fileName to the next file
fileName = Dir
Wend
End Sub
You seem to be showing two things:
The code to find all files you want to process.
The code you want to apply on the workbook in those files.
What you didn't to, is create a VBA workbook, based on the files you have found. This is explained in this URL.
Tried FaneDuru's code, it worked for the first time. After that, It was either shown as above which only has # or not responding.
I am fairly new to macro's, but I want to write a macro that opens a .csv file. Then, clears cell contents if the value is smaller than 10000 in a certain column. Then, save it and put it in a new csv file. My script is a mix of several topics on Stackoverflow.
I tried to write it and came to this:
Sub RemoveSmallValues()
Dim wb As Workbook
Dim myfilename As String
myfilename = "C:\Snapshot.csv"
'~~> open the workbook and pass it to workbook object variable
Set wb = Workbooks.Open(myfilename)
Dim r As Range, N As Long
Set r = ActiveSheet.Range("B1:B10")
N = Cells(Rows.Count, "C").End(xlUp).Row
For i = 1 To N
BB = Cells(i, "B").Value
If BB <= 10000 Then Range(BB).ClearContents
End If
Next i
Dim newfilename As String
newfilename = "C:\SnapshotBB.csv"
'~~> If you are saving it in a format other than .xlsx,
'~~> you have to be explicit in the FileFormat argument
wb.SaveAs newfilename, FileFormat:=xlOpenXMLWorkbook
wb.Close
End Sub
It would be great if you can help me!
Have a look at the below. I wasn't sure on some of the values that you wanted, so please TEST this before using on LIVE data.
To use this code. Please copy and paste the below into a MODULE.
I have also made a lot of assumptions, such as:
There are no BLANK cells in column C for the ROW COUNT
There are NO headers in your original CSV file (please see the comments for adjustments if this is not true).
Thanks
Sub RemoveSmallValues()
Dim myfilename As String
Dim myfilepath As String
Dim newfilename As String
Dim N As Long
Dim i As Long
Dim cellvalue As Long
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
'The above is just standard lines that I normally put into my code, enchances the speed of the macro.
myfilepath = "C:\Snapshot.csv"
myfilename = "Snapshot.csv"
Workbooks.Open (myfilepath)
Workbooks(myfilename).Activate 'Makes SnapShot.csv the active workbook
N = Range("C1", Range("C1").End(xlDown)).Rows.Count
'counts the number of rows untill cell is BLANK, based on your code I used Column C.
'If your columns have headers then you will need to make this C2. Otherwise your headers will be included and will create a datatype error on CELLVALUE
For i = 1 To N 'Again if your columns have hearders, then i will need to be i = 2
cellvalue = Cells(i, 2).Value
If cellvalue <= 10000 Then Cells(i, 2).ClearContents
Next i
newfilename = "C:\SnapshotBB" 'new file path and file name without extension.
Workbooks(myfilename).SaveAs newfilename, FileFormat:=xlCSV 'Save the file with extension CSV
ActiveWorkbook.Close False 'Close the workbook without saving, as you have already saved the workbook with line before.
End Sub
CSV Nightmare
Semicolon (;)
The problem is that my system saves csv files using the semicolon as separator by default. Excel will open the file normally, but VBA will open the file by putting the data from all columns into column A. The workaround is the checking for the number of columns. If there is only one column with data, the OpenText method is used with Local:=True. Now, the remaining problem is that VBA will save the file as comma separated , no matter if Local:=True, so when I open it in Excel, it will open all the columns in column A.
The Code
Sub RemoveSmallValues()
' Path of Source and Target Files
Const myPath As String = "D:\Excel\MyDocuments\StackOverflow\MyAnswers\Test"
Const myFile As String = "Snapshot.csv" ' Source File Name
Const newFile As String = "SnapshotBB.csv" ' Target File Name
Const myColumn As String = "B" ' Source/Target Column
Const myLRColumn As String = "C" ' Last-Row Column Letter
Const FR As Long = 1 ' First Row Number
Const cCrit As Long = 10000 ' Criteria Value
Dim wb As Workbook ' Source Workbook
Dim rng As Range ' Cell Ranges
Dim LR As Long ' Last Row
Dim BB As Long ' Current Value
Dim i As Long ' Source Worksheet Row Counter
Dim FPath As String ' Full Path
' Check if Source Workbook is already open.
For Each wb In Workbooks
' Source Workbook is open, stop looping.
If wb.Name = myFile Then Exit For
Next
' Calculate Full Path.
FPath = myPath & "\" & myFile
' Check if Source Workbook is not open.
If wb Is Nothing Then
' Handle error if Source Workbook could not be found.
On Error Resume Next
' Create a reference to Source Workbook.
Set wb = Workbooks.Open(FPath)
' Check if Source Workbook could not be found.
If Err Then ' Inform user and exit.
MsgBox "The file '" & myFile & "' could not be found in folder '" _
& myPath & "'.", vbCritical, "File not found"
Exit Sub
End If
On Error GoTo 0
End If
' Calculate Last Column in Source Worksheet.
Set rng = wb.ActiveSheet.Cells.Find("*", , xlValues, xlWhole, _
xlByColumns, xlPrevious)
' Check if all values are in first column.
If rng.Column = 1 Then
' Open Source Workbook as delimited file.
Workbooks.OpenText Filename:=FPath, _
DataType:=xlDelimited, Local:=True
' Create a reference to Source Workbook.
Set wb = ActiveWorkbook
' Calculate Last Column in Source Worksheet.
Set rng = wb.ActiveSheet.Cells.Find("*", , xlValues, xlWhole, _
xlByColumns, xlPrevious)
' Check if all values are still in first column.
If rng.Column = 1 Then ' Inform user and exit.
MsgBox "The file '" & myFile & "' in folder '" & myPath _
& "' is of an unsupported format.", vbCritical, _
"Unsupported format"
Exit Sub
End If
End If
With wb.ActiveSheet
' Calculate Last Row in Source Worksheet.
LR = .Cells(.Rows.Count, myLRColumn).End(xlUp).Row
' Loop through rows of Source Worksheet.
For i = FR To LR
' Check if the value in current cell is a number.
If IsNumeric(.Cells(i, myColumn).Value) Then
' Write value of current cell to Current Value.
BB = .Cells(i, myColumn).Value
' Check if Current Value meets Criteria.
If BB <= cCrit Then .Cells(i, myColumn).ClearContents
End If
Next
On Error Resume Next
' Save modified Source File as Target File.
' Note: This will save the file as COMMA separated anyway, no matter
' of the value of Local. Should be investigated.
.SaveAs Filename:=myPath & "\" & newFile, _
FileFormat:=xlCSV ', Local:=True ' This doesn't seem to help.
' Close Target File.
.Parent.Close False
On Error GoTo 0
End With
' Inform user of success.
MsgBox "Operation finished successfully.", vbInformation, "Success"
End Sub
So I want to automate a lot of manual work of copy/paste with the help of a Macro. The macro should read all files from folder one by one, copy the content from that source file range "I9:J172" and paste it on the destination file (where the macro is of course) on the column first blank row.
Application.ScreenUpdating = False
'For Each Item In franquicia
' OPEN THE SOURCE EXCEL WORKBOOK IN "READ ONLY MODE".
Set src = Workbooks.Open("C:\folder\inventory.xlsb", True, True)
' GET THE TOTAL ROWS FROM THE SOURCE WORKBOOK.
Dim iTotalRows As Integer
iTotalRows = src.Worksheets("INV").Range("I9:J" & Cells(Rows.Count, "J").End(xlUp).Row).Rows.Count
' FIND FIRST BLANK CELL
Dim LastRow As Long
LastRow = Worksheets("Hoja1").Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row
' COPY DATA FROM SOURCE (CLOSE WORKGROUP) TO THE DESTINATION WORKBOOK.
Dim iCnt As Integer ' COUNTER.
For iCnt = 1 To iTotalRows
Worksheets("Hoja1").Range("A" & LastRow & ":B" & iCnt).Value = src.Worksheets("INV").Range("I9:J172" & iCnt).Value
Next iCnt
' CLOSE THE SOURCE FILE.
src.Close False ' FALSE - DON'T SAVE THE SOURCE FILE.
Set src = Nothing
'Next Item
I want to solve first this last row problem and then do an array and the loop to read all the files one by one.
Thank you!
The following code does what you've described, and the animated gif demonstrates with 3 test files (with test data in the columns you mentioned). The first part of the gif shows the contents of 2 of the test files, and then runs the macro, stepping through it, showing the result on a "combined" sheet. Click on the gif to see better detail. Note that each test file's data must be on a "data" sheet. You can modify, of course.
Option Explicit
Dim theDir As String, alreadyThere As Boolean, wk As Workbook
Dim sh As Worksheet, comboSh As Worksheet, comboR As Range
Dim r As Range, s As String, numFiles As Integer
Const ext = ".xlsx"
Sub CombineFiles()
Set comboSh = getSheet(ThisWorkbook, "Combined", True)
theDir = ThisWorkbook.Path
s = Dir(theDir & "\*" & ext)
Set comboR = comboSh.Range("A1")
While s <> ""
ThisWorkbook.Activate
If comboR <> "" Then Set comboR = comboR.Offset(0, 2)
comboR.Activate
Set wk = Workbooks.Open(theDir & "\" & s)
Set sh = getSheet(wk, "data", False)
Set r = sh.Range("I9:J72")
'Set r = sh.Range(r, r.End(xlToRight))
'Set r = sh.Range(r, r.End(xlDown))
r.Copy
comboSh.Paste
Application.DisplayAlerts = False
wk.Close False
Application.DisplayAlerts = True
s = Dir()
numFiles = numFiles + 1
Wend
MsgBox ("done")
End Sub
Function getSheet(wk As Workbook, shName As String, makeIfAbsent As Boolean) As Worksheet
alreadyThere = False
For Each sh In wk.Worksheets
If sh.Name = shName Then
alreadyThere = True
Set getSheet = sh
End If
Next
If Not alreadyThere Then
If makeIfAbsent Then
Set getSheet = wk.Sheets.Add
getSheet.Name = shName
Else
MsgBox shName & " sheet not found -- ending"
End
End If
End If
End Function
I may be arriving to the party too late. It seems like you got the solution you were after. For future reference, try the AddIn below. This will do all kinds of copy/paste/merge tasks.
https://www.rondebruin.nl/win/addins/rdbmerge.htm
Below is the code I'm currently trying to run. The code works somewhat but the headers are copied from every worksheet and there is a significant gap in row count between where the data from the next file is copied. For example first file has 3600 row, the next data is copied in row 13,000. Any advice would be greatly appreciated.
Sub MergeAllWorkbooks()
Dim SummarySheet As Worksheet
Dim FolderPath As String
Dim NRow As Long
Dim FileName As String
Dim WorkBk As Workbook
Dim SourceRange As Range
Dim DestRange As Range
Dim LastRow As Long
' Create a new workbook and set a variable to the first sheet.
Set SummarySheet = Workbooks.Add(xlWBATWorksheet).Worksheets(1)
' Modify this folder path to point to the files you want to use.
FolderPath = "C:\Desktop\Files to Combine\"
' NRow keeps track of where to insert new rows in the destination workbook.
NRow = 1
' Call Dir the first time, pointing it to all Excel files in the folder path.
FileName = Dir(FolderPath & "*.xl*")
' Loop until Dir returns an empty string.
Do While FileName <> ""
' Open a workbook in the folder
Set WorkBk = Workbooks.Open(FolderPath & FileName)
' Set the source range to be A1 through BH and the last row.
' Modify this range for workbooks.
LastRow = ActiveSheet.Range("A" & Rows.Count).End(xlUp).Row
Set SourceRange = WorkBk.Worksheets(1).Range("A1:BH" & LastRow)
' Set the destination range to start at column A and
' be the same size as the source range.
Set DestRange = SummarySheet.Range("A1" & NRow)
Set DestRange = DestRange.Resize(SourceRange.Rows.Count, _
SourceRange.Columns.Count)
' Copy over the values from the source to the destination.
DestRange.Value = SourceRange.Value
' Increase NRow so that we know where to copy data next.
NRow = NRow + DestRange.Rows.Count
' Close the source workbook without saving changes.
WorkBk.Close savechanges:=False
' Use Dir to get the next file name.
FileName = Dir()
Loop
' Call AutoFit on the destination sheet so that all
' data is readable.
SummarySheet.Columns.AutoFit
End Sub
For row count issue, heed #ScottHoltzman's comments. Another issue too is a large amount of cells can be empty but are still in the used range as only their contents were cleaned but formatting remained. You may need to delete such cells from workbooks not just clear contents.
And to avoid repeat headers, condition the first file to bring over headers and all else to begin on row 2.
i = 1 ' INITIALIZE AN INT/LONG VARIABLE
Do While FileName <> ""
'...
If i = 1 Then
Set SourceRange = WorkBk.Worksheets(1).Range("A1:BH" & LastRow)
Else
Set SourceRange = WorkBk.Worksheets(1).Range("A2:BH" & LastRow)
End If
'...
i = i + 1 ' INCREMENT VARIABLE
FileName = Dir()
Loop