I have 2 folder, one source folder and one destination folder.
I want copy the sheet in position 1 form every excel source file, located in source folder, in corrispective destination excel file, located in destination folder.
To make it easier, the files have the same name, simply are in different folder.
I wrote the script below that works just for a single source and destination file. The script copy position 1 sheet from source to destination and rename it.
Sub MassCopy()
Dim wbk As Workbook
Dim SheetName
Dim Position
Dim SourceFile, DestinationFile
SheetName = "test_sheet"
Position = 1
SourceFile = "test1.xlsx"
DestinationFile = "test2.xlsx"
Windows(SourceFile).Activate
Sheets("Sheet1").Select
Sheets("Sheet1").Copy After:=Workbooks(DestinationFile).Sheets(Position)
Set wsNew = Sheets(Sheets(Position).Index + 1)
wsNew.Name = SheetName
End Sub
Is it possible to make it work for every file in source/destination folder?
Yes you can with a combination of of using LOOP and DIR. Below is the template that I use when I need to loop through a file folder and repeat the same action. Replace myPath with the file path to your folder and insert the code you want to run where I've indicated that you should enter your code.
Sub LoopThroughAllFiles()
Dim wb As Workbook
Dim myPath As String
Dim myFile As String
'Optimize Macro Speed
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
'Retrieve Target Folder Path From User
myPath = "C:\YourPath\TestFolder\"
myPath = myPath
If myPath = "" Then GoTo ResetSettings
'Target Path with Ending Extention
myFile = Dir(myPath)
'Loop through each Excel file in folder
Do While myFile <> ""
'Set variable equal to opened workbook
Set wb = Workbooks.Open(Filename:=myPath & myFile)
'Ensure Workbook has opened before moving on to next line of code
DoEvents
'Do your tasks
Enter the code for the tasks you want to accomplish here.
'Save and Close Workbook
wb.Close SaveChanges:=True
'Ensure Workbook has closed before moving on to next line of code
DoEvents
'Get next file name
myFile = Dir
Loop
ResetSettings:
'Reset Macro Optimization Settings
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
End Sub
Related
I looked everywhere and cannot find a fitting solution.
In my source workbook I have a range in sheet "Basics" which contains several filenames.
For example Range A1:A25
But not every cell in this range will contain a filename. Some will be empty.
I need a macro that opens all the listed files in range A1:A25, then copies Range A1:K500 from sheet1 in these files and then pastes this data to my source workbook into several sheets.
The several sheets in my source workbook are named 1, 2, 3, 4, 5 etc.
So the macro should open the first file listed in range A1:A25 and copy the data from Range A1:K500 from sheet1 from this workbook to sheet "1" (Range A1:K500) in my sourceworkbook. Then open second file + same task and paste to sheet "2" in source workbook and so on..
Thank you and best regards,
M
Ok here is what I have so far:
Sub LoopAllExcelFilesInFolder()
Dim wb As Workbook
Dim wb2 As Workbook
Dim myPath As String
Dim myFile As String
Dim myExtension As String
Dim FldrPicker As FileDialog
'Optimize Macro Speed
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
'Retrieve Target Folder Path From User
Set FldrPicker = Application.FileDialog(msoFileDialogFolderPicker)
With FldrPicker
.Title = "Select A Target Folder"
.AllowMultiSelect = False
If .Show <> -1 Then GoTo NextCode
myPath = .SelectedItems(1) & "\"
End With
'In Case of Cancel
NextCode:
myPath = myPath
If myPath = "" Then GoTo ResetSettings
'Target File Extension (must include wildcard "*")
myExtension = "*.xls*"
'Target Path with Ending Extention
myFile = Dir(myPath & myExtension)
'Loop through each Excel file in folder
Do While myFile <> ""
'Set variable equal to opened workbook
Set wb = Workbooks.Open(FileName:=myPath & myFile)
Set wb2 = ThisWorkbook
'Ensure Workbook has opened before moving on to next line of code
DoEvents
'Change First Worksheet's Background Fill Blue
wb.Worksheets(1).Range("A1:W500").Copy
---> Here is the the point where it needs to paste the copied data into sheet 1 of my workbook
---> After that the next external workbook is opened and the copied data will be pasted to sheet 2 of my workbook etc.
'Save and Close Workbook
wb.Close SaveChanges:=True
'Ensure Workbook has closed before moving on to next line of code
DoEvents
'Get next file name
myFile = Dir
Loop
'Message Box when tasks are completed
MsgBox "Task Complete!"
ResetSettings:
'Reset Macro Optimization Settings
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
End Sub
I'm looking for a help in a difficult mission.
I have more then 30.000 files in a especific folder (*\backup) in xl?? format and need to read the cell B4. I thought the better idea is use the VBA in Excel to read this specific cell for each file and write on a table A:B.
I believe the following should help you, just remember to amend the declaration for the destination Worksheet name and the full path to the folder where the Workbooks you want to read reside.
The code below will loop through your desired Directory/Folder and read all the files with an .xls* extension, get the value from the first Worksheet in cell B4 and pass this value to the destination worksheet.
Sub LoopAllExcelFilesInFolder()
Dim wb As Workbook
Dim myPath As String
Dim myFile As String
Dim myExtension As String
Dim wsDestination As Worksheet: Set wsDestination = ThisWorkbook.Worksheets("Sheet1")
'declare and set the worksheet where you want to aggregate the data.
'Optimize Macro Speed
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
Application.CutCopyMode = False
myPath = "C:\backup\"
'set the full path to the folder you want to utilize, remember to add the last \
Last = wsDestination.Cells(wsDestination.Rows.Count, "A").End(xlUp).Row
If Last >= 2 Then wsDestination.Range("A2:B" & Last).ClearContents
'clear the destination worksheet ready to aggregate again
myExtension = "*.xls*"
'Target File Extension (must include wildcard "*")
myFile = Dir(myPath & myExtension)
'Target Path with Ending Extention
Do While myFile <> ""
'Loop through each Excel file in folder
Set wb = Workbooks.Open(Filename:=myPath & myFile)
DoEvents
'Ensure Workbook has opened before moving on to next line of code
wsDestination.Cells(1, "A").Value = "Filename"
wsDestination.Cells(1, "B").Value = "Value From Cell B4"
NextRow = wsDestination.Cells(wsDestination.Rows.Count, "A").End(xlUp).Offset(1, 0).Row
wsDestination.Cells(NextRow, "A").Value = myFile
wsDestination.Cells(NextRow, "B").Value = wb.Worksheets(1).Range("B4").Value
wb.Close SaveChanges:=False
'Close Workbook without Saving
DoEvents
'Ensure Workbook has closed before moving on to next line of code
myFile = Dir
'Next File
Loop
MsgBox "Transfer of Data Completed!", vbInformation, "Info"
'Message Box when tasks are completed
ResetSettings:
'Reset Macro Optimization Settings
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
End Sub
I'm trying to save time in looking for excel files without a specific sheet named "RUNREADY" in a large directory of nested folders and excel files. This workbook without the worksheet would ideally be listed in a master excel file higher up in the directory or just have its name changed to end in a '(1)' or '(0)' depending on if it has the sheet or not.
Sub LoopAllExcelFilesInFolder()
'PURPOSE: To loop through all Excel files in a user specified folder and perform a set task on them
'SOURCE: www.TheSpreadsheetGuru.com
Dim wb As Workbook
Dim myPath As String
Dim myFile As String
Dim myExtension As String
Dim FldrPicker As FileDialog
'Optimize Macro Speed
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
'Retrieve Target Folder Path From User
Set FldrPicker = Application.FileDialog(msoFileDialogFolderPicker)
With FldrPicker
.Title = "Select A Target Folder"
.AllowMultiSelect = False
If .Show <> -1 Then GoTo NextCode
myPath = .SelectedItems(1) & "\"
End With
'In Case of Cancel
NextCode:
myPath = myPath
If myPath = "" Then GoTo ResetSettings
'Target File Extension (must include wildcard "*")
myExtension = "*.xls*"
'Target Path with Ending Extention
myFile = Dir(myPath & myExtension)
'Loop through each Excel file in folder
Do While myFile <> ""
'Set variable equal to opened workbook
Set wb = Workbooks.Open(Filename:=myPath & myFile)
'Ensure Workbook has opened before moving on to next line of code
DoEvents
'Change First Worksheet's Background Fill Blue
'wb.Worksheets(1).Range("A1:Z1").Interior.Color = RGB(51, 98, 174)
'Save and Close Workbook
wb.Close SaveChanges:=True
'Ensure Workbook has closed before moving on to next line of code
Dim ws As Worksheet
Dim rr As Integer
Dim cel As Range
rr = 0
For Each ws In ThisWorkbook.Worksheets
If ws.Name <> "RUNREADY" Then
rr = rr + 1
Else
rr = 0
End If
Next ws
If rr = 1 Then
[RUNREADY.xlsm] Sheet1!cel.Value = ActiveWorkbook.FullName
[RUNREADY.xlsm] Sheet1!cel.Offset(1, 0)
End If
'Get next file name
myFile = Dir
Loop
'Message Box when tasks are completed
MsgBox "Task Complete!"
ResetSettings:
'Reset Macro Optimization Settings
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
End Sub
I looked around for some sort of guidance and found this piece of code that searches through a file. I tried to write something that would write to a named excel file. my portion is spaced off in the middle of everything Running this i get an error at the first square bracket in my portion of code.
Im trying to copy data from a whole bunch of different workbooks into one master sheet, pasting just the values in the next blank column. It all seems to be functional but always fails when it attempts to paste into the master sheet. I've tried looking at similar problems elsewhere but i cant seem to get them to work with what I am trying to do.
I have grabbed the bulk of this code off somewhere else and modified to suit, as you may be able to tell from some of the left over comments
Sub LoopAllExcelFilesInFolder()
'PURPOSE: To loop through all Excel files in a user specified folder and perform a set task on them
'SOURCE: www.TheSpreadsheetGuru.com
Dim wb As Workbook
Dim myPath As String
Dim myFile As String
Dim myExtension As String
Dim FldrPicker As FileDialog
Dim colDest As Long
Dim Dest As Worksheet
'Optimize Macro Speed
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
'Retrieve Target Folder Path From User
Set FldrPicker = Application.FileDialog(msoFileDialogFolderPicker)
With FldrPicker
.Title = "Select A Target Folder"
.AllowMultiSelect = False
If .Show <> -1 Then GoTo NextCode
myPath = .SelectedItems(1) & "\"
End With
'In Case of Cancel
NextCode:
myPath = myPath
If myPath = "" Then GoTo ResetSettings
'Target File Extension (must include wildcard "*")
myExtension = "*.xls*"
'Target Path with Ending Extention
myFile = Dir(myPath & myExtension)
'Loop through each Excel file in folder
Do While myFile <> ""
'Set variable equal to opened workbook
Set wb = Workbooks.Open(fileName:=myPath & myFile)
'Ensure Workbook has opened before moving on to next line of code
DoEvents
'Change First Worksheet's Background Fill Blue this is where the work occurs
Set Dest = Workbooks("Master.xlsm").Worksheets(1)
colDest = Dest.Cells(1, Dest.Columns.Count).End(xlToRight).Column
wb.Worksheets(1).Range("b3:u83").Copy
Dest.Range(1, colDest).PasteSpecial Paste:=xlPasteValues
'Save and Close Workbook
wb.Close SaveChanges:=True
'Ensure Workbook has closed before moving on to next line of code
DoEvents
'Get next file name
myFile = Dir
Loop
'Message Box when tasks are completed
MsgBox "Task Complete!"
ResetSettings:
'Reset Macro Optimization Settings
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
End Sub
EDIT: Error occurs on this line:
Dest.Range(1, colDest).PasteSpecial Paste:=xlPasteValues
Run-time error '1004':
Method 'Range' of object '_Worksheet' failed.
EDIT2: Changing the attempt to Paste with an attempt to write a value to the cell ie:
Dest.Cells(1, colDest) = "Test"
Correctly types "Test" into the next available column on the master sheet for every workbook that was opened from the directory.
Apparently changing 'Range' to 'Cells' works, which i thought i tried yesterday but was throwing a different error complaining i wasn't selecting the correct size cell
Try this basically what you need to do is add 1 to the colDest to give you the next empty column.
Sub LoopAllExcelFilesInFolder()
'PURPOSE: To loop through all Excel files in a user specified folder and perform a set task on them
Dim wb As Workbook
Dim myPath As String
Dim myFile As String
Dim myExtension As String
Dim FldrPicker As FileDialog
Dim colDest As Long
Dim Dest As Worksheet
'Optimize Macro Speed
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
'Retrieve Target Folder Path From User
Set FldrPicker = Application.FileDialog(msoFileDialogFolderPicker)
With FldrPicker
.Title = "Select A Target Folder"
.AllowMultiSelect = False
If .Show <> -1 Then GoTo NextCode
myPath = .SelectedItems(1) & "\"
End With
'In Case of Cancel
NextCode:
myPath = myPath
If myPath = "" Then GoTo ResetSettings
'Target File Extension (must include wildcard "*")
myExtension = "*.xls*"
'Target Path with Ending Extention
myFile = Dir(myPath & myExtension)
'Loop through each Excel file in folder
Do While myFile <> ""
'Set variable equal to opened workbook
Set wb = Workbooks.Open(fileName:=myPath & myFile)
'Ensure Workbook has opened before moving on to next line of code
DoEvents
'Change First Worksheet's Background Fill Blue this is where the work occurs
Set Dest = Workbooks("Master.xlsm").Worksheets(1)
colDest = Dest.Cells(1, Dest.Columns.Count).End(xlToLeft).Column + 1
wb.Worksheets(1).Range("b3:u83").Copy
Dest.Range(1, colDest).PasteSpecial Paste:=xlPasteValues
'Save and Close Workbook
wb.Close SaveChanges:=True
'Ensure Workbook has closed before moving on to next line of code
DoEvents
'Get next file name
myFile = Dir
Loop
'Message Box when tasks are completed
MsgBox "Task Complete!"
ResetSettings:
'Reset Macro Optimization Settings
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
End Sub
Below are some guidelines on how to find last column an import value after last column.
Option Explicit
Sub Test()
Dim LastColumn As Long
With ThisWorkbook.Worksheets("Sheet1")
'Last Column using UsedRange (NOT A GOOD IDEA)
LastColumn = .UsedRange.Columns(.UsedRange.Columns.Count).Column
'Last Column using specific row 7
LastColumn = .Cells(7, .Columns.Count).End(xlToLeft).Column
'Add a value in row 5 & after last column
.Cells(5, LastColumn + 1).Value = ""
End With
End Sub
Set Dest = Workbooks("Master.xlsm").Worksheets(1)
colDest = Dest.Cells(1, Dest.Columns.Count).End(xlToLeft).Column + 1
wb.Worksheets(1).Range("b3:u83").Copy
Dest.Cells(1, colDest).PasteSpecial Paste:=xlPasteValues
Correctly inputs the Data where I need it, the 'ToLeft' made a difference but 'Range' wouldn't allow me to paste where 'Cells' does
I know similar questions have been asked, but I've tried all the solution codes with no success. I'm a beginner in VBA and What I'm trying to accomplish is:
Copy files from sfol to dfol
For each file now in dfol, if "summary" tab exists, change cell I3
For each file in dfol, if "sheet2" tab exists, change pivot filter
The code runs and the changes are complete for the first file in dfol, but it doesn't even open each of the rest of the files. I need it to open every file. Also as a side note, the final msgbox at the end does not pop-up, so I'm thinking the code doesn't even run its full course.
Sub GenerateReports()
'Generate Seed Run Validation Reports Macro
Dim wb As Workbook
Dim MainFile, dfol, sfol As String
Dim vDate, Fname, myExtension As String
Dim wsCount As Integer
Dim fso
Application.ScreenUpdating = False
Application.DisplayAlerts = False
'Confirm the user wants to proceed
If MsgBox("Compile?", vbYesNo) = vbNo Then Exit Sub
'Define current workbook
MainFile = ThisWorkbook.Name
'Define Dates
vDate = "Potato"
'Set file path
sfol = "I:\ABCFolder"
dfol = "I:\DEFFolder"
'Copy all files from source folder
Set fso = CreateObject("Scripting.FileSystemObject")
fso.CopyFolder sfol, dfol
'Target Path with extension
myExtension = "*.xls*"
dfol = dfol & "\"
Fname = Dir(dfol & myExtension)
'Loop through files in folder
Do While Fname <> ""
Set wb = Workbooks.Open(fileName:=dfol & Fname)
'Ensure workbook opened
DoEvents
wsCount = wb.Worksheets.Count
For i = 1 To wsCount
'Update Date on Summary tab
If wb.Worksheets(i).Name = "Summary" Then
wb.Worksheets(i).Range("I3") = vDate
End If
Next i
'save changes and close
wb.Close SaveChanges:=True
'Ensure workbook closed
DoEvents
'Get next file name
Fname = Dir
Loop
'***************************** End of Macro ***************************
Application.ScreenUpdating = True
Application.DisplayAlerts = True
MsgBox ("Assumptions Compiled!")
End Sub
Additional problems:
Every time a file is opened, I get asked if I want to update the links. I need it just not update.
I will also need to rename all the files in the folder starting with "2017..." to be, say, "2018..."
Any help is greatly appreciated!
You can specify not to update links when opening.
Set wb = Workbooks.Open(fileName:=dfol & Fname, UpdateLinks:=false)
Use SaveAs to change the name of the open workbook.
wb.saveas FileName:=replace(wb.name, "2017", "2018")
After the SaveAs, wb will be the new copy of the original.
Use on error resume next for a more direct route to changing data on the Summary worksheet.
on error resume next
with wb.worksheets("summary")
.Range("I3") = vDate
end with
on error goto 0