Close all files in a folder - excel

I have the following code that opens all files in a specified folder
Sub OpenFiles()
Dim MyFolder As String
Dim MyFile As String
MyFolder = "\\ILAFILESERVER\Public\Documents\Renewable Energy\FiTs\1 Planning Department\Marks Tracker\Quality Control Reports"
MyFile = Dir(MyFolder & "\*.xlsx")
Do While MyFile <> ""
Workbooks.Open Filename:=MyFolder & "\" & MyFile
MyFile = Dir
Loop
End Sub
Is it possible to have a similar code that closes all files in the folder. Many thanks in advance for any assistance provided on this matter.

Workbooks.Open will return a reference to the pointer of the workbook. Save this in a Collection (using Collection.Add) as soon as you open the workbook. When you want to close all the workbooks, iterate through the collection (using For Each) and close each element. Then remove all elements from the collection.

Try
Workbooks.Close
From the Excel Visual Basic Help documentation:
This example closes all open workbooks. If there are changes in any open workbook, Microsoft Excel displays the appropriate prompts and dialog boxes for saving changes.

Do you need to have them all open at the same time? Because otherwise:
Sub OpenFiles()
Dim MyFolder As String
Dim MyFile As String
MyFolder = "\\ILAFILESERVER\Public\Documents\Renewable Energy\FiTs\1 Planning Department\Marks Tracker\Quality Control Reports"
MyFile = Dir(MyFolder & "\*.xlsx")
Dim wb As Workbook
Do While MyFile <> ""
Set wb = Workbooks.Open Filename:=MyFolder & "\" & MyFile
'Do stuff
wb.Close False 'The false will close without saving
MyFile = Dir
Loop
End Sub

Related

Update file references while looping

I'm trying to loop through files in a folder and take data for that files using references, im using below code , but still getting Update Values window popped up at every file in which I have to manually select path of files. How to do this reference automatically
[Salary.Value is name of a cell in files in that folder]
Dim myfolder As String
Dim myfile As String
Dim wbk As Workbook
With Application.FileDialog(msoFileDialogFolderPicker)
.Title = "please select a folder"
.Show
.AllowMultiSelect = False
myfolder = .SelectedItems(1) & "\"
End With
myfile = Dir(myfolder)
Do While myfile <> ""
Set wbk = Workbooks.Open(Filename:=myfolder & myfile)
' the next line is the one in question
Range("I6").FormulaR1C1 = "='myfile'!Salary.value"
myfile = Dir
Loop
End Sub
A browse window named update values is popping up
'MyFile' is a variable name. But how you use it, it is considered as name of the workbook.
Try
Range("I6").FormulaR1C1 = "='" + MyFile + "'!Salary.value"
instead

Open files in a loop using Dir

I want to open a file, copy from it then paste to another document, copy from that and paste back into the opened document.
I converted the file names to strings and it recognizes that but says they don't exist.
Dim StrFile As String
'Debug.Print "in LoopThroughFiles. inputDirectoryToScanForFile: ", inputDirectoryToScanForFile
StrFile = Dir("H:\Open Work book" & "\" & "*.xlsx")
Do While Len(StrFile) > 0
StrFile = Dir
'Opens The File In The folder
Workbooks.Open StrFile
This should open the files in a loop. It says
Sorry, we couldn't find CTM Service Reach.xlsx. Is it possible it was moved renamed or deleted?
When you execute
StrFile = Dir("H:\Open Work book" & "\" & "*.xlsx")
strfile gets filled with the first file matching the pattern. You check that something is returned
Do While Len(StrFile) > 0
but then you change strfile into the next file meeting the pattern - throwing away the first file's name
StrFile = Dir
Then you attempt to open the file without specifying where it is
Workbooks.Open StrFile
what you should be doing is
StrFile = Dir("H:\Open Work book" & "\" & "*.xlsx")
Do While Len(StrFile) > 0
Workbooks.Open "H:\Open Work book" & "\" & StrFile
StrFile = Dir
Loop
I know, you have your solution but, hey, like the Romans used to say: variatio delectat. Here's another way of doing this:
Sub test()
Dim objFSO As Object
Dim objFolder As Object
Dim objFile As Object
Dim strDir As String
Dim wkb As Workbook
strDir = "H:\Open Work book\"
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder(strDir)
For Each objFile In objFolder.Files
If objFSO.GetExtensionName(objFile) = "xlsx" Then
Set wkb = Workbooks.Open(objFile)
// You code here
End If
Next
End Sub

Cannot open Workbook in read/write mode

I'm trying to apply different macros to every excel file present in a folder adding several sheets to them, and to do so I'm looping over all the files in the folder and opening them one by one.
However, I stumbled upon the issue that, every workbook I open is in read only mode, thus preventing me from saving it after having modified it.
Setting the ReadOnly parameter to False, and the IgnoreReadOnlyRecommended parameter to True doesn't change anything, and the workbook still opens as a read only workbook.
Sub RunOnAllFilesInFolder()
Dim folderName As String, fileName As String
Dim wb As Workbook
folderName = "H:\mypath"
fileName = Dir(folderName & "\*.xlsx")
Debug.Print (fileName)
Do While fileName <> ""
Set wb = Workbooks.Open(fileName:=folderName & "\" & fileName, ReadOnly:=False, IgnoreReadOnlyRecommended:=True)
MsgBox (wb.ReadOnly)
wb.Activate
Call my_sub
Application.DisplayAlerts = False
wb.SaveAs (folderName & "\" & fileName)
wb.Close SaveChanges:=False
Set wb = Nothing 'clean up
Application.DisplayAlerts = True
Debug.Print "Processed " & folderName & "\" & fileName
fileName = Dir()
Loop
End Sub
Would anyone know why the file opens as a read only file (despite being just a regular excel file), or another way to modify these files and save the changes?

VBA how to open/save/close file with extension from one folder

I need to write a VBA script in which i need to go to one folder and open file with specific extension (txt) and save without making any changes and then close the file.
It should loop in the folder and open,save ,close all the file with txt extension.
Set objFSO = CreateObject("Scripting.FileSystemObject")
objStartFolder = "U:\test"
Set objFolder = objFSO.GetFolder(objStartFolder)
Wscript.Echo objFolder.Path
Set colFiles = objFolder.Files
For Each objFile in colFiles
If UCase(objFSO.GetExtensionName(objFile.name)) ="txt" Then
colFiles.Activate
colFiles.save
colFiles.closedoc
End If
Next
Please help
if i understood your question you need of this code:
Dim MyFolder As String
Dim MyFile As String
MyFolder = "U:\test" //path
MyFile = Dir(MyFolder & "\*.txt") //get all file with extension .txt
Do While MyFile <> ""
Workbooks.Open Filename:=MyFolder & "\" & MyFile //open file *.txt
Workbooks(MyFile).Close SaveChanges:=True //close file and save
MyFile = Dir //next file *.txt
Loop
I tried this code and works fine.
Hope this help you.
EDIT post:
try this one, copy and paste only, in your macro module
Sub controlFile()
Dim MyFolder As String
Dim MyFile As String
MyFolder = "U:\test" 'path
MyFile = Dir(MyFolder & "\*.txt") 'get all file with extension .txt
Do While MyFile <> ""
Workbooks.Open Filename:=MyFolder & "\" & MyFile 'open file *.txt
Workbooks(MyFile).Close SaveChanges:=True 'close file and save
MyFile = Dir 'next file *.txt
Loop
End Sub
Keep me updated..(i used office 2013 and 2007 on owindows 10 and macro works fine).I don't obtain anything error.
When execute macro use f8 button to execute one code row at time

VBA to open Word document and refresh links

I am hoping to find a solution (be it VBA or not) to my problem. I have a Word document with linked Excel tables in it. All links work correctly, but I have to manually open the Word document in order for it to refresh with the Excel data. The reason I am using Word instead of Excel is due to the large amounts of text.
Is there a way that I could program some sort of code that would go through all Word documents in a folder, open each document, refresh all links, save document, and move onto the next one?
Here's what I have so far
Sub OpenFiles()
Dim MyFolder As String
Dim MyFile As String
MyFolder = "LOCATION"
MyFile = Dir(MyFolder & "\*.docx")
Do While MyFile <> ""
Documents.Open Filename:=MyFolder & "\" & MyFile
MyFile = Dir
Loop
End Sub
UPDATE
Ok I was able to make the open files command work! Now I am attempting to make it overwrite/save the file and close it.
Error Message: Object Required
Sub OpenFiles()
Dim MyFolder As String
Dim MyFile As String
Dim objWord As Object
Set objWord = CreateObject("Word.Application")
objWord.Visible = True
MyFolder = "LOCATION"
MyFile = Dir(MyFolder & "\*.docx")
Do While MyFile <> ""
objWord.Documents.Open Filename:=MyFolder & "\" & MyFile
Application.DisplayAlerts = False
ActiveDocument.SaveAs Filename:=MyFile
Application.DisplayAlerts = True
MyFile = Dir
Loop
End Sub
You can try any of below:
Dim objDoc As Object
Do While Myfile <> ""
Set objDoc = objWord.Documents.Open(Filename:=MyFolder & "\" & MyFile)
objDoc.Save '~~> Save
objDoc.Close '~~> Close
Myfile = Dir
Loop
Or you can just use Close Method like this.
objDoc.Close True '~~> close with SaveChanges argument set to True

Resources