Loop through xlsm files, getting error 438 - vba

I took some code from here and I can not manipulate it.
Wanna iterate through few xlsm files in one directory. So that each row from single xlsm file will be shown in a Summary Workbook.
unfortunately , i get error 438, probably beacuse of the Dim methode.
Please help me figure it out :)
Sub MergeAllWorkbooks()
Dim SummarySheet As Workbook
Dim FolderPath As String
Dim NRow As Long
Dim FileName As String
Dim WorkBk As Workbook
Dim SourceRange As Range
Dim DestRange As Range
Application.Calculation = xlCalculationAutomatic
' open summary workbook .
Set SummarySheet = ThisWorkbook
' Modify this folder path to point to the files you want to use.
FolderPath = "C:\Projects\SuperProject\BorotNisayon\"
' NRow keeps track of where to insert new rows in the destination workbook.
NRow = 2
' Call Dir the first time, pointing it to all Excel files in the folder path.
FileName = Dir(FolderPath & "*.xlsm")
' Loop until Dir returns an empty string.
Do While FileName <> ""
' Open a source workbook in the folder
Set WorkBk = Workbooks.Open(FolderPath & FileName)
' Set the source range to be A2 through P2.
' Modify this range for your workbooks.
' It can span multiple rows.
Set SourceRange = WorkBk.Sheets("Drill").Range("A2:P2")
' Set the destination range to start at column B and
' be the same size as the source range.
Set DestRange = SummarySheet.Range("A2:P2" & NRow)
' Copy over the values from the source to the destination.
DestRange.Value = SourceRange.Copy
' 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
End Sub

Related

Combining Excel workbooks, but need the all worksheets, not just the first

I found this VBA code that works for combining workbooks in a folder, however, I need to modify it so that all worksheets in each workbook are copy/pasted and not just the first worksheet of each workbook. As of now, only the first worksheet in each selected workbook is being copied over. Where can I insert code to find data in all worksheets?
Thanks!
Sub MergeSelectedWorkbooks()
Dim SummarySheet As Worksheet
Dim FolderPath As String
Dim SelectedFiles() As Variant
Dim NRow As Long
Dim FileName As String
Dim NFile As Long
Dim WorkBk As Workbook
Dim SourceRange As Range
Dim DestRange As Range
' 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 = "S:\example"
' Set the current directory to the the folder path.
ChDrive FolderPath
ChDir FolderPath
' Open the file dialog box and filter on Excel files, allowing multiple files
' to be selected.
SelectedFiles = Application.GetOpenFilename( _
filefilter:="Excel Files (*.xl*), *.xl*", MultiSelect:=True)
' NRow keeps track of where to insert new rows in the destination workbook.
NRow = 1
' Loop through the list of returned file names
For NFile = LBound(SelectedFiles) To UBound(SelectedFiles)
' Set FileName to be the current workbook file name to open.
FileName = SelectedFiles(NFile)
' Open the current workbook.
Set WorkBk = Workbooks.Open(FileName)
Dim LastRow As Long
LastRow = WorkBk.Worksheets(1).Cells.Find(What:="*", _
After:=WorkBk.Worksheets(1).Cells.Range("A1"), _
SearchDirection:=xlPrevious, _
LookIn:=xlFormulas, _
SearchOrder:=xlByRows).Row
Set SourceRange = WorkBk.Worksheets(1).Range("A1:Z" & LastRow)
' Set the destination range to start at column A and be the same size as the source range.
Set DestRange = SummarySheet.Range("A" & 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
Next NFile
' Call AutoFit on the destination sheet so that all data is readable.
SummarySheet.Columns.AutoFit
End Sub
Opens multiple workbooks (1 by 1), Copies data from all sheets onto one sheet. Make sure you modify the ranges that will work for you (copy range is currently A2 to Z(last row).
Option Explicit
Sub MoveSheets()
Dim IndvFiles As FileDialog
Dim Currentbook As Workbook
Dim x As Integer
Dim i As Integer
Dim CurrentSheets As Integer
Dim BookCount As Integer
'Opens File Dialog to Select Which Files You Want to Consolidate
Set IndvFiles = Application.FileDialog(msoFileDialogOpen)
With IndvFiles
.AllowMultiSelect = True
.Title = "Multi-select target data files:"
.ButtonName = ""
.Filters.Clear
.Show
End With
Application.ScreenUpdating = False
Application.DisplayAlerts = False
CurrentSheets = ThisWorkbook.Worksheets.Count
BookCount = IndvFiles.SelectedItems.Count
Dim LROW as Long
DIM LROW2 as Long
DIM Import as Range
For x = 1 To BookCount
On Error GoTo StopHere:
Set Currentbook = Workbooks.Open(IndvFiles.SelectedItems(X))
For i = 1 To Currentbook.Worksheets.Count
LROW = thisworkbook.sheets("desired sheet name paste").Range("A2").End(XLdown).Rows
LROW2=currentbook.sheets(i).Range("A2").End(XLdown).Rows
Set Import = currentbook.sheets(i).Range("A2:Z"&LROW2)
Import.Copy
ThisWorkbook.Sheets("Desired sheet name paste range").Range("A"&LROW).PasteSpecial Paste:=xlPasteValues, operation:=xlNone, skipblanks _
Next i
Currentbook.Close False
Next x
StopHere:
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub

VBA to copy sheets from all files in folder and copy it to master

I have a folder full of multiple excel files and all of the files have a specific sheet that i need to copy into my master.
I need macro to open all files in that folder one by one and copy the specific sheet to the master file using the source file name as sheet name in the master workbook. Excel 2013.
I tried searching online and have the following code:
Option Explicit
Sub test()
Dim wkbDest As Workbook
Dim wksDest As Worksheet
Dim wkbSource As Workbook
Dim wksSource As Worksheet
Dim MyPath As String
Dim MyFile As String
Application.ScreenUpdating = False
Set wkbDest = ThisWorkbook
Set wksDest = wkbDest.Worksheets("Sheet1") 'change the destination sheet name accordingly
MyPath = "H:\Cutover\"
If Right(MyPath, 1) <> "\" Then MyPath = MyPath & "\"
MyFile = Dir(MyPath & "*.xls")
Do While Len(MyFile) > 0
Set wkbSource = Workbooks.Open(MyPath & MyFile)
Set wksSource = wkbSource.Worksheets("Sheet1") 'change the source sheet name accordingly
'Your copy/paste code here (((((need help here please))))))))
wkbSource.Close savechanges:=False
MyFile = Dir
Loop
Application.ScreenUpdating = True
MsgBox "Completed...", vbInformation
End Sub
EDIT:
So i manage to get to the below however its still not working properly. It doesn't rename the sheet to the source filename. Can someone please help?
Option Explicit
Sub test()
Dim wkbDest As Workbook
Dim wksDest As Worksheet
Dim wkbSource As Workbook
Dim wksSource As Worksheet
Dim MyPath As String
Dim MyFile As String
Application.ScreenUpdating = False
Set wkbDest = ThisWorkbook
Set wksDest = wkbDest.Worksheets("Sheet1") 'change the destination sheet name accordingly
MyPath = "H:\Cutover\"
If Right(MyPath, 1) <> "\" Then MyPath = MyPath & "\"
MyFile = Dir(MyPath & "*.xlsx")
Do While Len(MyFile) > 0
Set wkbSource = Workbooks.Open(MyPath & MyFile)
Set wksSource = wkbSource.Worksheets("Sheet1") 'change the source sheet name accordingly
Sheets("SheetToCopy").Copy Before:=Workbooks("WorkbookToPasteIn").Sheets(SheetIndex)
wkbSource.Close savechanges:=False
MyFile = Dir
Loop
Application.ScreenUpdating = True
MsgBox "Completed...", vbInformation
End Sub
so the part you need help with is how to copy/paste a range from a worksheet in one file to a common worksheet in a destination file?
set up a variable to track the last empty row in the destination sheet
look up how to determine what the last row is in each source sheet, select that source range, copy it into the clipboard, and then paste it at the last empty row in the destination sheet, and reset the destination variable to the new first blank row in the destination sheet
an alternative way of doing it would be to open an output CSV file, and parse each row and build up a string and write it to the file without closing the output CSV file until the loop is over
if the files are large tho, it would be much better to use VB.NET instead as it is much faster at dealing with large files
you could also read each file/row into an in-memory datatable and then output the datatable to a CSV file, or to the destination Excel file
which method would you prefer?
You could simply copy your sheet in the new workbook, following this code:
Sheets("SheetToCopy").Copy Before:=Workbooks("WorkbookToPasteIn").Sheets(SheetIndex)
And then, rename the sheet to fit your means.

excel macro not copying cells correctly

I have adapted a VBA macro I found online in order to copy lots (50+) xls files into one big excel worksheet in a new file. They all have the same columns.
Works just fine, but I noticed that some of the excel files have a crucial value inserted as string instead of number.
Copying that string results in a "wrong" number: if origin is 3099,213 my result is 3.099.213 (european notation with comma for decimals and dot for thousands), so x1000 in size.
My question: how can I copy so that the format is maintained? I can then later easily convert the string into number in the outputfile without problem.
Sub MergeSelectedWorkbooks()
Dim SummarySheet As Worksheet
Dim FolderPath As String
Dim SelectedFiles() As Variant
Dim NRow As Long
Dim FileName As String
Dim NFile As Long
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 = "G:\gas 2016-2017\distribution\CLASS\0351\"
' Set the current directory to the the folder path.
ChDrive FolderPath
ChDir FolderPath
' Open the file dialog box and filter on Excel files, allowing multiple files
' to be selected.
SelectedFiles = Application.GetOpenFilename( _
filefilter:="Excel Files (*.xl*), *.xl*", MultiSelect:=True)
' NRow keeps track of where to insert new rows in the destination workbook.
NRow = 1
' Loop through the list of returned file names
For NFile = LBound(SelectedFiles) To UBound(SelectedFiles)
' Set FileName to be the current workbook file name to open.
FileName = SelectedFiles(NFile)
' Open the current workbook.
Set WorkBk = Workbooks.Open(FileName)
' Set the cell in column A to be the file name.
SummarySheet.Range("A" & NRow).Value = FileName
LastRow = WorkBk.Worksheets(1).Cells.Find(What:="*", _
After:=WorkBk.Worksheets(1).Cells.Range("A1"), _
SearchDirection:=xlPrevious, _
LookIn:=xlFormulas, _
SearchOrder:=xlByRows).Row
Set SourceRange = WorkBk.Worksheets(1).Range("A8:Z" & LastRow)
' Set the destination range to start at column B and be the same size as the source range.
Set DestRange = SummarySheet.Range("B" & 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
Next NFile
' Call AutoFit on the destination sheet so that all data is readable.
SummarySheet.Columns.AutoFit
End Sub
Can you use IsNumber on the 2nd row of the current column to see if it is a number, then when you bring in the value into the new sheet, set as val(SourceRange.Value)?

Select additional worksheets when merging workbooks

I am trying to parse data from multiple workbooks with multiple sheets into a single workbook that summarizes the data. So far I have been able to combine a specified range of data, from multiple workbooks, into a single file. However I would like to also include data from the worksheets within the workbooks.
How do I modify the range to include additional worksheets?
'Creates a new workbook
'Reads data
'Writes data to the workbook
'Format the data in the workbook
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
' 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:\attach\"
' 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 & "*.xlsx*")
' 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
' Here Is where I need to specify additional sheets, I think.
' Modify this range for your workbooks.
' It can span multiple rows.
Set SourceRange = WorkBk.Worksheets(2).Range("A1:B7") <====
' Set the destination range to start at column B and
' be the same size as the source range.
Set DestRange = SummarySheet.Range("B" & 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

open folder, manipulate files in excel, save excel files in new directory

I have a folder called "maildir". It contains folders named numerically. These folders contain text files.
I have hacked together a macro that opens the numerically named folder, opens its first text file, and copies the contents into Excel. It then opens the next file in the directory, and copies the new file into a new sheet in the same workbook.
Then, the procedure deletes all the rows below row five, for every sheet in the workbook.
The next step combines the content from all the sheets into a new sheet called "Combined".
Then, all sheets but "Combined" are deleted
The next step saves the workbook into a new folder called "enron_excel".
This is where I am stuck: I was able to get the macro to work fine until I added a "For Loop" which is designed to both open the numerically named folders, and save them with numerical names in the "enron_excel" folder.
But when I run the code, and look in the "enron_excel" folder, it seems that the "combined" step has been missed. Does anyone know what happened?
Thank you.
Sub all()
Application.DisplayAlerts = False
Dim J As Integer
Dim ws As Worksheet
Dim wks As Worksheet
For i = 1 To 3 ' What I want this for loop to do: open the file called "1" (and later 2 and 3), manipulate the data then save with the same number in a different file
Path = "C:\Users\Kate\Desktop\enron4\maildir\" ' open folder in a directory
Filename = Dir(Path & i & "*.txt") ' opens a folder, and a text file in that folder
Do While Filename <> "" ' opens file in folder and copies to sheet in excel workbook
Workbooks.Open Filename:=Path & Filename, ReadOnly:=True
For Each Sheet In ActiveWorkbook.Sheets
Sheet.Copy After:=ThisWorkbook.Sheets(1)
Next Sheet
Workbooks(Filename).Close
Filename = Dir()
Loop
For Each ws In ThisWorkbook.Worksheets ' deletes all the rows below row five
ws.Range("5:1000").Delete
Next ws
On Error Resume Next
Sheets(1).Select ' combines all the sheets into one worksheet
Worksheets.Add
Sheets(1).Name = "Combined"
Sheets(2).Activate
Range("A1").EntireRow.Select
Selection.Copy Destination:=Sheets(1).Range("A1")
For J = 2 To Sheets.Count
Sheets(J).Activate
Range("A1").Select
Selection.CurrentRegion.Select
Selection.Offset(1, 0).Resize(Selection.Rows.Count - 1).Select
Selection.Copy Destination:=Sheets(1).Range("A65536").End(xlUp)(2)
Next J
Sheets("Combined").Select ' selects the sheet calls "Combined" and deletes all the others
Application.DisplayAlerts = False
For Each wks In Worksheets
If wks.Name <> ActiveSheet.Name Then wks.Delete
Next wks
Path = "C:\Users\Kate\Desktop\enron_excel\" ' this opens a new path
FolderName = i
ActiveWorkbook.SaveAs Filename:=Path & FolderName ' this saves the file in the new path with the new name
Application.DisplayAlerts = True
Next i
End Sub
Why don't you use File System Object.
Something like:
Sub ReadAllfiles()
Dim fso As Scripting.FileSystemObject
Dim sFile As Scripting.File
Dim subFldr As Scripting.Folder
Dim wbName As String
Dim fldrPath As String
Dim fname As String
Dim fldrDesc As String
Dim wbTxt As Workbook
Dim ws As Worksheet
Dim wbDesc As Workbook
fldrDesc = "C:\User\Yourdestination\" '<~~ change to suit
fldrPath = "C:\User\Yourfolder" '<~~ change to suit
'iterate each folder of your source folder
Set fso = New Scripting.FileSystemObject
For Each subFldr In fso.GetFolder(fldrpath).SubFolders
wbName = subFldr.Name
Set wbDesc = Workbooks.Add 'add a new workbook
'create the combined sheet
Set ws = wbDesc.Sheets(1): ws.Name = "Combined"
'iterate each file on the folder
For Each sFile In subFldr.Files
fname = sFile.ParentFolder.Path & "\" & sFile.Name
Set wbTxt = Workbooks.Open(fname)
'I'm not sure why a text file will yield to multiple sheet
'so if that is really the case use your loop
'copy the 1st 4 rows to Combined sheet
wbTxt.Sheets(1).Range("1:4").Copy _
ws.Range("A" & ws.Rows.Count).End(xlUp).Offset(1, 0)
wbTxt.Close False 'close source text file
Next
wbDesc.SaveAs fldrDesc & wbName 'save the workbook
wbDesc.Close True 'close
Next
End Sub
I just based it on how you describe what you want. Not tested though.
You will need to add reference to Microsoft Scripting Runtime. HTH.