You can switch from one open MS Word document to another by pressing CTRL + F6, in case you didn’t know.
But what if you have 16 Word documents open for some reason and you’d like to know their total number and view their file names so that you can decide whether to switch to them or perhaps close them off if you don’t need them anymore?
By writing a little VBA code, you can create a simple macro that would do exactly that.
(1) First select one of the open Word documents.
(2) Press ALT + F11 to display the VBA editing screen.
(3) Insert a new module by selecting Insert > Module from the menu.
(4) Insert the following subprocedure code in your Code Pane:
(5) Click the GREEN RUN ARROW on the toolbar, or press F5 key, or select Run > Run Sub/User Form from the menu to run the subprocedure.
If Word displays a macro selecting dialog box, select the macro and click Run.
After you run the macro, Microsoft Word will display a MsgBox (Message Box) like the following:
The exact content of the MsgBox will depend on the number of Word documents currently open.
P.S. If you’d like to learn how the VBA code exactly works, please leave a comment and I’d be happy to help.
Is there any other MS Word tasks and challenges that you cannot accomplish through the normal Word controls and tools but would like to do it through VBA code? Please let me know.
(Free image courtesy of Pippalou at morguefile.com)
I have the following code:
Sub WordtoTxtwLB()
'
' WordtoTxtwLB Macro
'
'
Dim fileName As String
myFileName = ActiveDocument.Name
ActiveDocument.SaveAs2 fileName:= _
"\FILE" & myFileName & ".txt", FileFormat:= _
wdFormatText, LockComments:=False, Password:="", AddToRecentFiles:=True, _
WritePassword:="", ReadOnlyRecommended:=False, EmbedTrueTypeFonts:=False, _
SaveNativePictureFormat:=False, SaveFormsData:=False, SaveAsAOCELetter:= _
False, Encoding:=1252, InsertLineBreaks:=True, AllowSubstitutions:=False, _
LineEnding:=wdCRLF, CompatibilityMode:=0
End Sub
I want to loop this sub through all of the word (.doc) files in a directory. I have the following code:
Sub LoopDirectory()
vDirectory = "C:programs2test"
vFile = Dir(vDirectory & "" & "*.*")
Do While vFile <> ""
Documents.Open fileName:=vDirectory & "" & vFile
ActiveDocument.WordtoTxtwLB
vFile = Dir
Loop
End Sub
But it is not working. How do I get this to work either by altering the current code or using new code?
title | keywords | f1_keywords | ms.prod | api_name | ms.assetid | ms.date | ms.localizationpriority |
---|---|---|---|---|---|---|---|
Application.Documents property (Word) |
vbawd10.chm158334982 |
vbawd10.chm158334982 |
word |
Word.Application.Documents |
7e477cb3-ae65-685a-0083-1826efe86703 |
06/08/2017 |
medium |
Application.Documents property (Word)
Returns a Documents collection that represents all the open documents. Read-only.
Syntax
expression.Documents
expression A variable that represents an Application object.
Remarks
For information about returning a single member of a collection, see Returning an object from a collection.
[!NOTE]
A document displayed in a Protected View window is not a member of the Documents collection. Instead, use the Document property of the ProtectedViewWindow object to access a document that is displayed in a Protected View window.
Example
This example creates a new document based on the Normal template and then displays the Save As dialog box.
This example saves open documents that have changed since they were last saved.
Dim docLoop As Document For Each docLoop In Documents If docLoop.Saved = False Then docLoop.Save Next docLoop
This example prints each open document after setting the left and right margins to 0.5 inch.
Dim docLoop As Document For Each docLoop In Documents With docLoop .PageSetup.LeftMargin = InchesToPoints(0.5) .PageSetup.RightMargin = InchesToPoints(0.5) .PrintOut End With Next docLoop
This example opens Doc.doc as a read-only document.
Documents.Open FileName:="C:FilesDoc.doc", ReadOnly:=True
See also
Application Object
[!includeSupport and feedback]
In this article I will explain how you can use VBA for word to open multiple files and modify them.
–
Step 1:
Put all the word documents that you want to modify in one folder. Note the file with the VBA code should be kept somewhere else.
–
Step 2:
Use an open folder dialog to get the folder path from the user. I’ve explained about open file dialogs in the article below:
- VBA Folder Dialog
The code below will display an open folder dialog and request the user select a folder:
Sub Example1()
Dim intResult As Integer
Dim strPath As String
'the dialog is displayed to the user
intResult = Application.FileDialog(msoFileDialogFolderPicker).Show
'checks if user has cancled the dialog
If intResult <> 0 Then
'dispaly message box
strPath = Application.FileDialog( _
msoFileDialogFolderPicker).SelectedItems(1)
End If
End Sub
If the user selects a folder, the path will be stored in the variable strPath.
–
Step 3:
Get the list of all the file paths in the folder. I have explained how this can be done in the article below:
- Find and List All Files and Folder in a Directory
Although that article was aimed for Excel, the concept can also be applied to VBA for Word. The function below recieves as input the path of the folder. It returns a string array with the path of all the files in the folder.
Private Function GetAllFilePaths(ByVal strPath As String) As String()
Dim objFSO As Object
Dim objFolder As Object
Dim objFile As Object
Dim i As Integer
Dim arrOutput() As String
ReDim arrOutput(1 To 1)
'Create an instance of the FileSystemObject
Set objFSO = CreateObject("Scripting.FileSystemObject")
'Get the folder object
Set objFolder = objFSO.GetFolder(strPath)
i = 1
'loops through each file in the directory and prints
'their names and path
For Each objFile In objFolder.Files
ReDim Preserve arrOutput(1 To i)
'print file path
arrOutput(i) = objFile.Path
i = i + 1
Next objFile
GetAllFilePaths = arrOutput
End Function
Assume we have the following files in a folder:
The code below uses the function above to get all the files in the folder:
Sub Example2()
Dim strPath As String
Dim arrFiles() As String
strPath = "D:StuffBusinessTemp"
arrFiles = GetAllFilePaths(strPath)
End Sub
Result:
–
Step 4:
The function below recieves as input the path of a word document, opens it, clears all the data and prints the text string “some data” in the document:
Private Sub ModifyFile(ByVal strPath As String)
Dim objDocument As Document
Set objDocument = Documents.Open(strPath)
objDocument.Activate
Selection.WholeStory
Selection.Delete
Selection.Range.Text = "Some Data"
objDocument.Close (True)
End Sub
This was only for illustrative purposes. You could apply any other modification required.
–
Complete Code:
Below you can see the complete code:
Sub Example1()
Dim intResult As Integer
Dim strPath As String
Dim arrFiles() As String
Dim i As Integer
'the dialog is displayed to the user
intResult = Application.FileDialog(msoFileDialogFolderPicker).Show
'checks if user has cancled the dialog
If intResult <> 0 Then
'dispaly message box
strPath = Application.FileDialog( _
msoFileDialogFolderPicker).SelectedItems(1)
arrFiles() = GetAllFilePaths(strPath)
For i = LBound(arrFiles) To UBound(arrFiles)
Call ModifyFile(arrFiles(i))
Next i
End If
End Sub
Private Sub ModifyFile(ByVal strPath As String)
Dim objDocument As Document
Set objDocument = Documents.Open(strPath)
objDocument.Activate
Selection.WholeStory
Selection.Delete
Selection.Range.Text = "Some Data"
objDocument.Close (True)
End Sub
Private Function GetAllFilePaths(ByVal strPath As String) _
As String()
Dim objFSO As Object
Dim objFolder As Object
Dim objFile As Object
Dim i As Integer
Dim arrOutput() As String
ReDim arrOutput(1 To 1)
'Create an instance of the FileSystemObject
Set objFSO = CreateObject("Scripting.FileSystemObject")
'Get the folder object
Set objFolder = objFSO.GetFolder(strPath)
i = 1
'loops through each file in the directory and
'prints their names and path
For Each objFile In objFolder.Files
ReDim Preserve arrOutput(1 To i)
'print file path
arrOutput(i) = objFile.Path
i = i + 1
Next objFile
GetAllFilePaths = arrOutput
End Function
You can download the file and code related to this article from the link below:
- Modify Multiple Files.docm
See also:
- Word VBA, Open Document
- Word Automation VBA, Common Errors
- Word VBA, Modify Header For Multiple Files
- Word Automation VBA, Common Errors
- VBA, Write Excel Values to Word Document
- VBA, Automating Word From Excel
If you need assistance with your code, or you are looking for a VBA programmer to hire feel free to contact me. Also please visit my website www.software-solutions-online.com
I am making an excel project to manage the creation and filing of a set of word documents created from the same .dotx template. I dont have experience with vba for MS Word. The requisit MS References are open to use the Word Object model.
Before moving or copying a word document using scripting.FileSystemObject, I wish to identify if the file in question is OPEN, and close it before move/copy.
I thought that one documents collection would cover all open Word application windows, and that this code would report all open docs:
Sub tstDocsOpen()
Dim aDoc As Word.Document
Dim aName As String
aName = «»
For Each aDoc In Word.Documents
aName = aName & aDoc.Name & vbCr
Next aDoc
MsgBox aName
End Sub
However, when I open two docs in separate windows, sometimes one is reported (twice), and sometimes both reported. Changing which windows file has most recently been ‘on top’ made no difference.
Please can you help?
Kelvin4
Word |
Print All Open Documents |
|
Ease of Use |
Easy |
|
Version tested with |
2000 |
|
Submitted by: |
TonyJollans |
|
Description: |
A simple routine to print all documents currently open. |
|
Discussion: |
For all sorts of reasons you may have multiple Word documents open and want to print all of them at one go. This will do it for you — you can run it from any document, or even from normal.dot. |
|
|
instructions for use |
|
|
||
How to use: |
|
|
Test the code: |
|
|
Sample File: |
No Attachment |
|
Approved by Anne Troy |
||
This entry has been viewed 62 times. |
||