VBA looping through each file in folder - excel

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

Related

Specify name of sheet in VBA

I have this vba code that puts sheet1 of all workbooks in a folder in as sheets in one workbook. This works all fine.
What I want to do is change the name of each sheet that is copied in to my workbook. Then I want to overwrite the files that already exists in the workbook.
Hope someone can help me with a solution.
Sub CombineFilesInSheets()
Dim Path As String
Dim FileName As String
Dim Wkb As Workbook
Dim WS As Worksheet
Application.EnableEvents = False
Application.ScreenUpdating = False
Path = "*The path*" 'Change as needed
FileName = Dir(Path & "\*.xls", vbNormal)
Do Until FileName = ""
Set Wkb = Workbooks.Open(FileName:=Path & "\" & FileName)
Worksheets("Sheet1").Copy After:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count)
Wkb.Close False
FileName = Dir()
Loop
Application.EnableEvents = True
Application.ScreenUpdating = True
End Sub
There are a couple ways to go about your request, and not to steal from /u/VBasic2008, but he's on a similar line of thinking to me.
'open workbook like you do
Set Wkb = Workbooks.Open(FileName:=Path & "\" & FileName)
'perform your regular copy
Worksheets("Sheet1").Copy After:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count)
'define a name
dim desiredSheetName as string
desiredSheetName = Wkb.Name 'takes the workbook name
'check if the desired name exists, and if so, delete the old sheet
If Not IsError(Evaluate(desiredSheetName & "!A1")) Then ThisWorkbook.Sheets(desiredSheetName).Delete
'name the last added sheet in ThisWorkbook the desired name
ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count).Name = desiredSheetName
You could similarly use the check to do nothing if the desiredSheetName already exists, though I believe the above fits your post.
I fixed this by running a macro afterwards to delete and edit names of sheets

Rename Files - Only After All Have been opened (to ensure links update to new file location and names)

I have 50 files that are linked to each other to varying degrees. Each month all files must be moved to a different folder (new issue) with updated names to reflect the new month (ie. Sales 445F - 06-2019 to Sales 446F - 07-2019).
To do so, I believe I need to open all 50 files, before renaming, so that the links will be updated to the new name and the new file location.
Below is the macro I created keying off a column that identifies the files to be opened and then a second column that identifies the new name of the file.
Although the macro creates new files in the right location with the right names, the files created are all the same (the last file opened) and the links still remain attached to the old file names and locations. Suggestions?
Private Sub CommandButton1_Click()
For i = 10 To 59
pathname = Range("B5").Value
Filename = Range("B" & i).Value
Application.AskToUpdateLinks = False
Application.DisplayAlerts = False
Workbooks.Open Filename:=pathname & Filename
Next i
MsgBox ("All Files Have Been Opened")
For i = 10 To 59
pathname2 = Range("C5").Value
filename2 = Range("C" & i).Value
ActiveWorkbook.SaveAs Filename:=pathname2 & filename2
Next i
MsgBox ("All Files Have Been Saved in the New Folder. A Final Save to Update Links to Point to the New Folder Will Now Begin")
Dim wb As Workbook
Dim wbStayOpen1 As String
Dim currentwb As String
wbStayOpen1 = "C:\Users\Desktop\Custom Macros\Open Rename and Save to New Folder.xlsm"
currentwb = ThisWorkbook.Name
For Each wb In Workbooks
If wb.Name <> wbStayOpen1 And wb.Name <> currentwb Then
wb.Close SaveChanges:=True
End If
Next wb
Application.AskToUpdateLinks = True
Application.DisplayAlerts = True
End Sub
It always saves the exact same workbook because you use ActiveWorkbook.SaveAs and the active one does never change. Avoid using ActiveWorkbook. Instead set all workbooks to an array of opened workbooks wbOpen(iStart To iEnd) that you can easily access then in your second loop. And also use it to close them in your third loop.
Never number your variable names. This is a very bad practice and if you think you need to do that you are doing something wrong. Actually there is no need to declare pathname2 and filename2 you can re-use the first variable.
Option Explicit
Private Sub CommandButton1_Click() 'make sure to give it a proper name
Dim wsSource As Worksheet
Set wsSource = ThisWorkbook.ActiveSheet 'better declare sheet name like `ThisWorkbook.Worsheets("Sheet1")
'if the start and end is dynamic make them variables instead of constants
Const iStart As Long = 10
Const iEnd As Long = 59
ReDim wbOpen(iStart To iEnd) As Workbook
Dim PathName As String
Dim FileName As String
'open workbooks
Dim i As Long
For i = iStart To iEnd
PathName = wsSource.Range("B5").Value
FileName = wsSource.Range("B" & i).Value
Application.AskToUpdateLinks = False
Application.DisplayAlerts = False
Set wbOpen(i) = Workbooks.Open(FileName:=PathName & FileName)
Next i
MsgBox ("All Files Have Been Opened")
'save workbooks
For i = iStart To iEnd
PathName = wsSource.Range("C5").Value
FileName = wsSource.Range("C" & i).Value
wbOpen(i).SaveAs FileName:=PathName & FileName
Next i
MsgBox ("All Files Have Been Saved in the New Folder.")
'close workbooks
For i = iStart To iEnd
wbOpen(i).Close SaveChanges:=True
Next i
Application.AskToUpdateLinks = True
Application.DisplayAlerts = True
End Sub

Referencing Non-Active Workbook Using Macro in Personal Workbook

I have a macro that works in any Excel workbook but doesn't work once I place it in my PERSONAL.XLSB file. My goal is to take the tabs from all of the files in a folder on my desktop and copy them into the active file. I know the issue is that I am using This.Workbook as the location reference for the copied tabs but I don't know how else to reference the workbook I am trying to copy the tabs into. I don't want to reference a filepath for where to copy the tabs since this will be used by multiple people in multiple files. Any thoughts would be greatly appreciated.
Sub CombineWorkbooks()
Dim Path As Variant
Path = GetFolder(1) & "\"
Dim FileName As String
FileName = Dir(Path & "*.xl??")
Dim ws As Worksheet
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Do While FileName <> ""
Workbooks.Open Path & FileName
For Each ws In ActiveWorkbook.Sheets
ws.Copy after:=ThisWorkbook.Worksheets(ThisWorkbook.Worksheets.Count)
Next ws
Workbooks(FileName).Close
FileName = Dir()
Loop
Application.ScreenUpdating = True
Application.DisplayAlerts = True
Exit Sub
End Sub
If you define the file to a variable or activeworkbook it should work.
UPDATED as I think I slightly misunderstood the overall objective of macro but the concept is still the same. Let me know if this doesn't work.
Sub CombineWorkbooks()
Dim Path As Variant
Path = GetFolder(1) & "\"
Dim FileName As String
FileName = Dir(Path & "*.xl??")
Dim ws As Worksheet, wkBkToCopyTo As Workbook
Set wkBkToCopyTo = ActiveWorkbook 'assuming that you run this with the destination open.
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Do While FileName <> ""
Workbooks.Open Path & FileName
For Each ws In ActiveWorkbook.Sheets
ws.Copy after:=wkBkToCopyTo.Worksheets(wkBkToCopyTo.Worksheets.Count)
Next ws
Workbooks(FileName).Close
FileName = Dir()
Loop
Application.ScreenUpdating = True
Application.DisplayAlerts = True
Exit Sub
End Sub
You could also try to find it based on its name:
'you could also use a loop to find it
For Each wkBkToCopyTo In Application.Workbooks
If InStr(1, wkBkToCopyTo.Name, "someNameof the workbook", vbTextCompare) > 0 Then
Exit For
End If
Next wkBkToCopyTo

Read a file and creat a table

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

Mass Copy Excel Sheet from many sources

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

Resources