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
Related
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
I am trying to go through a number of folders with files in side of them. Extract some data from the same range in each of the files and put it on the next blank row within my master spreadsheet. This is called Wb in the code. The code is looping through a folder with subfolders inside.
Sub LoopFolders()
' Declaring variables
Dim myFolder As String
Dim mySubFolder As String
Dim myFile As String
Dim collSubFolders As New Collection
Dim myItem As Variant ' This means that excel will decide what kind of variable it is
Dim wbk As Workbook
Dim Wb As Workbook
Set Wb = ThisWorkbook
' set parent folder with trailing backslash
myFolder = "F:\Documents\Ad-hoc\Loop\"
'Retrieve first sub-folder
' * is the wildcard character
mySubFolder = Dir(myFolder & "*", vbDirectory)
Application.ScreenUpdating = False
'Do While Not mySubFolder = ""
Do While mySubFolder <> ""
Select Case mySubFolder
Case ".", ".." ' . refers to current folder, .. refers to the parent folder
' ignore current folder or parent folder
Case Else
' Add to collection called collSubFolders
'collSubFolders.Add Item:=mySubFolder, Key:=mySubFolder
collSubFolders.Add Item:=mySubFolder
End Select
' Get next entry
mySubFolder = Dir
Loop
' Loop through the collection
For Each myItem In collSubFolders
' Loop through Excel workbooks (with any extension) in subfolder
myFile = Dir(myFolder & myItem & "\*.xls*")
Do While myFile <> ""
' Open workbook
DoEvents
Set wbk = Workbooks.Open(Filename:=myFolder & myItem & "\" & myFile)
' Copy data from the opened workbook
' starting from row 2 and column 1 to row 3 and column 2 and copying it
ActiveSheet.Range(Cells(2, 1), Cells(3, 2)).Copy
---here the code breaks and an error 400 is shown----
' Close opened workbook without saving any changes
wbk.Close SaveChanges:=False
Wb.Activate
erow = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row
ActiveSheet.Cells(erow, 1).Select
ActiveSheet.Paste
ActiveWorkbook.Save
Application.CutCopyMode = False
myFile = Dir
Loop
Next myItem
Application.ScreenUpdating = True
End Sub
I've spent some time trying to work out why this might be the case. One thing I found was that when I hover my mouse over the wbk variable it shows nothing even after I have f8'ed through it. The document does open but, after that when it is asked to locate the range on the new active file it cannot cope. Does anyone know why this might be the case?
Also note: the looping through the folders works fine and I can see that by going through it step by step. It is the part I mentioned above that although seems simple seems to not be working.
use:
debug.print myFolder & myItem & "\" & myFile
it is most likely that your path is wrong.
My guess would be that you have a problem with: myFile
Because first you execute:
myFile = Dir(myFolder & myItem & "\*.xls*") and then you execute:
Filename:=myFolder & myItem & "\" & myFile
Which translates into:
Filename:=myFolder & myItem & "\" & Dir(myFolder & myItem & "\*.xls*")
I am new here but found below to open docx, refresh (linked table from Excel), and save multiple Word document in folder which is working fine. However I want to add one more procedure to produce PDF format as well before Quit the Document. So I will have both docx and pdf files in same folder.
Search so much but still cannot find the answer. Appreciated if you can help…
Dim MyFolder As String
Dim MyFile As String
Dim objWord As Object
Dim objDoc As Object
Set objWord = CreateObject("Word.Application")
objWord.Visible = True
MyFolder = "D:\PPM for Dashboard"
MyFile = Dir(MyFolder & "\*.docx")
Do While MyFile <> ""
Set objDoc = objWord.Documents.Open(FileName:=MyFolder & "\" & MyFile)
objDoc.Save
MyFile = Dir
Loop
objWord.Quit
Set objWord = Nothing
The method to save a word document as PDF is ExportAsFixedFormat. It has numerous parameters, see the documentation at Microsoft, but basically you just need to provide a filename. If you omit the 2nd parameter (ExportFormat), word will check the extension of the filename to decide, however, is does no harm to tell word what you want (use the constant wdExportFormatPDF)
The following routine saves an open word doc as PDF in the same folder and with the same name (it assumes that the document itself is already saved, else it don't have a valid file name).
Sub saveAsPDF(wordDoc As Word.Document)
Dim fName As String, p As Integer
fName = wordDoc.FullName
p = InStrRev(fName, ".")
fName = Left(fName, p) & "pdf"
wordDoc.ExportAsFixedFormat fName, wdExportFormatPDF
End Sub
In your existing loop, you just have to add a call to this procedure:
Do While MyFile <> ""
Set objDoc = objWord.Documents.Open(FileName:=MyFolder & "\" & MyFile)
objDoc.Save
saveAsPDF objDoc
objDoc.Close
MyFile = Dir
Loop
Update: The code above uses early binding, so a reference to the Word Object Library is needed. To use late binding (as the OP does), change the routine to:
Sub saveAsPDF(wordDoc As Object)
Const wdExportFormatPDF = 17
Dim fName As String, p As Integer
fName = wordDoc.FullName
p = InStrRev(fName, ".")
fName = Left(fName, p) & "pdf"
wordDoc.ExportAsFixedFormat fName, wdExportFormatPDF
End Sub
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
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