VBA Code
Documents
Documents can have several windows and windows can have several panes.
Each document has at least one corresponding window associated with it.
ActiveDocument - Refers to the document that is currently active.
ThisDocument - Refers to the document that contains the code. This is only relevant to document-level solutions. If you have an application-level add-in then this is not relevant.
Windows
Each window contains a Panes collection containing all the corresponding Pane objects
Application.ActiveWindow.Panes(1).Activate
Panes
Normally a window contains just one pane.
It is however possible to split a window into multiple panes. Each Pane is represented by its own Pane object.
Task Panes
wdTaskPanes.wdTaskPaneHelp
Application.TaskPanes(wdTaskPaneFormatting).Visible = True
Dim TheTaskPane as String
TheTaskPane = CommandBars("Task Pane").Controls(1).Caption
Application.ScreenRefresh
Application.KeyBindings - key shortcuts
Application.RecentFiles - 50 most recently opened
Application.TaskPanes
Application.DefaultSaveFormat
Document.StoryRanges
Range.TextRetrievalMode.IncludeFieldCodes =
VBA Windows
Windows("Temp.doc").Activate
Windows(2).Activate
ActiveWindow.Caption
ActiveWindow.DisplayRulers
ActiveWindow.DisplayScreenTips
ActiveWindow.DisplayVerticalRuler
ActiveWindow.DisplayVerticalScrollBar
ActiveWindow.DocumentMap
ActiveWindow.Split = True / False
ActiveWindow.PrintOut
ActiveWindow.WindowNumber
ActiveWindow.PageFit = wdPageFit.wdPageFotNone
ActiveWindow.WindowState = wdWindowState.wdWindowStateNormal
An error will occur if this is applied to an inactive window.
Multiple Windows
It is also possible to create multiple windows of the same document.
The Document object has a Window property that returns the collection of all the window objects associated with that given document.
objWindow.Activate
If (Windows(1).Active = True) Then
'this window is currently active
End If
Dim objDocument As Document
objDocument = ActiveWindow.Document
Creating new Windows
Windows.Add(Window)
The window object is the window you want to duplicate
If the Window object is missing then a new window of the active document is created.
This is the number of open windows.
Windows.Count
When there are multiple windows open for a document the window caption is appended with a colon and a number.
Application.NewWindow
objWindow.NewWindow
ActiveWindow.NewWindow
Arranging Windows
Windows.Arrange(wdArrangeStyle.wdIcons)
Application.WindowState = wdWindowState.wdWindowStateMaximize
Understanding the difference between Selecting and Activating
To make a different document the active document you can use the Activate method of the Document object.
Documents("document.doc").Activate
Navigating
Scrolls the number of lines, the default is 1 line
ActiveWindow.SmallScroll
Scrolls the number of screens, the default is 1 screen
ActiveWindow.LargeScroll
ActiveWindow.ActivePane.LargeScroll Down:=
Up:=
ToRight:=
ToLeft:=
Scrolls the numbe of document pages, default is 1 page down
This does not affect the position of the insertion point.
This is only available in Print Layout or Online View
ActiveWindow.PageScroll Down:=
Up:=
This returns or sets the scroll bar position as a percentage of the document width
ActiveWindow.HorizontalPercentScrolled
ActiveWindow.HorizontalPercentScrolled = 50
ActiveWindow.VerticalPercentScrolled
Closing Windows
This closes the active window of the active document and saves it.
ActiveDocument.ActiveWindow.Close SaveChanges:=wdSaveOptions.wdSaveChanges, _
RouteDocument:=False
VBA Panes
A lot of windows related properties are actually properties of the Pane object which is associated with the window.
If the View is not Print Layout then the Panes collection can contain such things as comments and footnotes.
Application.ActiveWindow.Panes(1).Activate
View
Each pane can be displayed in a different view
Application.ActiveWindow.ActivePane.View.Type = wdViewType.wdPrintView
Zoom
Each pane can be displayed with a different View percentage
Application.ActiveWindow.ActivePane.View.Zoom.PageFit = wdPageFit.wdPageFitBestFit
You can also specify an exact percentage.
Application.ActiveWindow.ActivePane.View.Zoom.Percentage = 125
Application.ActiveWindow.ActivePane.Zooms(wdViewType.wdNormalView).Percentage = 125
Displaying 2 pages next to each other
With Application.ActiveWindow.ActivePane.View.Zoom
.PageColumns = 2
.PageRows = 1
End With
This example sets the zoom percentage in Print Layout view so that an entire page is visible
Application.ActiveWindow.ActivePane.Zooms(wdViewType.wdPrintView).PageFit = wdPageFit.wdPageFitFullPage
This example sets the zoom percentage in Normal view to 100% for all the open windows
Dim objWindow As Window
For Each objWindow In Application.Windows
objWindow.ActivePane.Zooms(wdViewType.wdNormalView).Percentage = 100
Next objWindow
Closing Panes
ActiveDocument.ActiveWindow.ActivePane.Close
VBA Documents
Documents.Add
Creating a blank document based on the Normal template
This method returns the document that was created.
Documents.Add
Set objDocument = Documents.Add
Creating a new document based on a different template
The new document will become the active document
Application.Documents.Add DocumentType:=wdNewDocumentType.wdNewBlankDocument
Application.Documents.Add Template:="C:\Temp\Template.dot"
NewTemplate:=
DocumentType:=wdNewDocumentType.wdNewBlankDocument, _
Visible:=True)
Template - (Optional) The name of the template to be used for the new document. The default is the Normal template
NewTemplate - (Optional) Whether to open the document as a template. The default is False
DocumentType - (Optional) The type of new document to create. The default is NewBlankDocument
Visible - (Optional) Whether the new document is visible. The default is True
Creating a copy of the active document
Application.Documents.Add Template:=ActiveDocument.FullName
Document File Name
This line will return the filename of the active document.
Application.ActiveDocument.Name = Document1.doc
ActiveDocument.Name = Document1.doc
Application.Documents.Item(2).Name
If the active document has not been saved yet then this returns the filename with no extension
ActiveDocument.Name = Document2
You can check if a document has been saved or not by checking if the following are the same
If (ActiveDocument.Name = ActiveDocument.FullName) Then
'document has not been saved yet
End If
Document Folder
This line returns the folder path of where the document is saved
Application.ActiveDocument.Path
ActiveDocument.Path
If the active document has not been saved then this is blank ???
Document Folder and FileName
This returns the full folder path and the filename
ActiveDocument.FullName
This line is equivalent to the following
ActiveDocument.Path & ActiveDocument.PathSeparator & ActiveDocument.Name
Looping Through Open Documents
Dim icount As Integer
For icount = 1 To Application.Documents.Count
If (Application.Documents(icount).Name - "Document1") Then
End If
Next icount
A lot of windows related properties are actually properties of the Pane object which is associated with the window.
This line will create an error if there is no document currently open
If (Application.Documents.Count > 1) Then
sName = ActiveDocument.Name
End If
Set objRange = ActiveDocument.Content
Set objRange = ActiveDocument.Range
VBA Opening
You can use the Open method of the Documents collection to open an existing document.
This will open a document and will add it to the Documents collection.
The Format argument corresponds to the file converter to be used to open the document.
Application.Documents.Open FileName:="C:\Temp\document.doc", _
ConfirmConversions:=False, _
ReadOnly:=False, _
AddToRecentFiles:=True, _
PasswordDocument:="", _
PasswordTemplate:="", _
Revert:=
WritePasswordDocument:="", _
WritePasswordTemplate:="", _
Format:=wdOpenFormat.wdOpenFormatAuto
Encoding:=msoEncoding.msoEncodingWestern
Visible:=True, _
OpenConflictDocument:=
OpenAndRepair:=False, _
DocumentDirection:=wdDocumentDirection.wdLeftToRight, _
NoEncodingDialog:=False, _
XMLTransform:=
FileName -
ConfirmConversions - Pass true to display the Convert File dialog box if the filename passed to Open is not in Word format.
ReadOnly - Pass true to open the document as read-only. If the document is already set to read-only on disk, passing false will not affect the read-only status of the document. The default is False.
AddToRecentFiles - Pass true to add a filename to the list of recently used files. The default is True.
PasswordDocument - Pass a string representing the password for opening the document if the document is password protected
PasswordTemplate - Pass a string representing the password for opening the template if the template is password protected
Revert - If the document you are opening with the Open method is already open in Word, pass true to discard any unsaved changes in the already open document. Pass False to activate the already-open document.
WritePasswordDocument - Pass a string representing the password for saving changes to the document if the document is password protected.
WritePasswordTemplate - Pass a string representing the password for saving changes to the template if the template is password protected.
Format - Pass an wdOpenFormat enumeration specifying the file conversion to be used when opening the file.
Encoding - Pass an Office.MsoEncoding enumeration specifying the code page or character set to be used when you open the document.
Visible - Pass True to open the document in a visible window. The default is True.
OpenConflictDocument - Pass true to open the conflict file for a document that has offline conflicts.
OpenAndRepair - Pass true to try and repair a corrupted document.
DocumentDirection - A member of wdDocumentDirection enumeration specifying the horizontal flow of text in the document.
NoEncodingDialog - Pass true to prevent Word from displaying the encoding dialog box if the text encoding of the document cannot be determined.
The Open method can also return a document object referring to the document that has just been opened.
Dim objDocument As Document
objDocument = Application.Documents.Open FileName:="C:\Temp\document.doc"
The Documents property is global so the Application property is optional.
objDocument = Application.Documents.Open FileName:="C:\Temp\document.doc"
Current Folder
If you do not provide a folder path then the document is assumed to be in the current folder.
Documents.Open(FileName:="document.doc")
However it is good practice to always specify the full folder path though.
Documents.Open(FileName:="C:\Temp\document.doc"
Confirm Conversions
If this argument is set to True the Convert File dialog box will be displayed if the file isn't in Microsoft Word format.
Read Only
This argument doesn't override the read-only recommended setting on a saved document.
For example, if a document has been saved with read-only recommended turned on, setting the ReadOnly argument to False will not cause the file to be opened as read/write.
Revert
Controls what happens if FileName is the name of an open document.
True to discard any unsaved changes to the open document and reopen the file. False to activate the open document.
Encoding
The document encoding (code page or character set) to be used by Microsoft Word when you view the saved document.
The default value is the system code page.
Visible
In Word 2000 if you open a Document with the Visible argument set to False the document is not added to the Documents or the Windows collections.
objDocument = Application.Documents.Open FileName:="C:\Temp\document.doc", _
Visible:=False
No Encoding
True to skip displaying the Encoding dialog box that Word displays if the text encoding cannot be recognized. The default value is False.
Using a system independent path separator
Windows uses the path separator "\"
Macintosh uses the path seperator ":"
Application.PathSeperator
This returns the correct path seperator for the current file system.
Application.Options.DefaultOpenFormat = wdOpenFormat.wdOpenFormatDocument
You can return an open Document object using the Documents collection.
Dim objDocument As Document
Set objDocument = Documents("filename.doc")
Set objDocument = Documents(1)
Because the index number can change when you open and close documents it is always safer to use the actual filename.
VBA Closing
Application.ActiveDocument.Close SaveChange:=wdSaveOptions.wdPromptToSaveChanges
OriginalFormat:=wdOriginalFormat.wdPromptUser
RouteDocument:=False
All these arguments are optional
The RouteDocument is optional and can be set to True to route the document to the next recipient
If the document does not have a routing slip attached then this argument is ignored.
Application.Documents("document.doc").Close
Documents("document.doc").Close
Documents(1).Close
objDocument.Close
Close all Documents without saving
You can use the Documents collection to quickly close all the currently open documents.
Application.Documents.Close SaveChange:=wdSaveOptions.wdDoNotSaveChanges
Exiting Word
Application.Quit SaveChanges:=wdSaveOptions.wdPromptToSaveChanges
Format:=wdOriginalFormat.wdWordDocument
RouteDocument:=False
VBA Saving
Document.Save
If the document or template hasn't been saved before, this method will display the Save As dialog box and prompt the user to save the file.
Application.ActiveDocument.Save
ActiveDocument.Save
Application.Documents("document.doc").Save
Documents("document.doc").Save
objDocument.Save
If the user presses the Cancel button on the SaveAs dialog box then an error will be generated.
To prevent this error you must catch the error and ignore it by using an On Error .. Command.
Document.Saved
This property indicates if there are any unsaved changes in the document
It can also be set as a way of getting a document to close without a "do you want to save changes" prompt
Changing the property to True will flag the document as clean and disable the save button
If (ActiveDocument.Saved = False) Then
End if
Document.SaveAs
Display the SaveAs dialog box allowing you to save a copy of that document or template.
ActiveDocument.SaveAs FileName:="C:\Temp\document.doc", _
FileFormat:=wdSaveFormat.wdFormatDocument, _
LockComments:=False, _
Password:=""
AddToRecentFiles:=True
WritePassword:=""
ReadOnlyRecommendation:=False
EmbedTrueTypeFonts:=False
SaveNativePictureFormat:=False
SaveFormatData:=False
SaveAsOCELetter:=False
Encoding:=
InsertLineBreaks:=
AllowSubstitutions:=
LineEnding:=
AddBiDiMarks:=
FileName - The name for the document. The default is the current folder and file name. If the document has never been saved, the default name is used (for example, Doc1.doc). If a document with the specified file name already exists, the document is overwritten without the user being prompted first.
FileFormat -The format in which the document is saved. Can be any WdSaveFormat value. To save a document in another format, specify the appropriate value for the SaveFormat property.
LockComments - true to lock the document for comments. The default is false.
Password - A password string for opening the document. (See Remarks below.)
AddToRecentFiles - true to add the document to the list of recently used files on the File menu. The default is true.
WritePassword - A password string for saving changes to the document. (See Remarks below.)
ReadOnlyRecommended - true to have Microsoft Office Word suggest read-only status whenever the document is opened. The default is false.
EmbedTrueTypeFonts - true to save TrueType fonts with the document. If omitted, the EmbedTrueTypeFonts argument assumes the value of the EmbedTrueTypeFonts property.
SaveNativePictureFormat - If graphics were imported from another platform (for example, Macintosh), true to save only the Windows version of the imported graphics.
SaveFormsData - true to save the data entered by a user in a form as a data record.
SaveAsAOCELetter - If the document has an attached mailer, true to save the document as an AOCE letter (the mailer is saved).
Encoding - MsoEncoding. The code page, or character set, to use for documents saved as encoded text files. The default is the system code page.
InsertLineBreaks - If the document is saved as a text file, true to insert line breaks at the end of each line of text.
AllowSubstitutions - If the document is saved as a text file, true allows Word to replace some symbols with text that looks similar. For example, displaying the copyright symbol as (c). The default is false.
LineEnding - The way Word marks the line and paragraph breaks in documents saved as text files. Can be any WdLineEndingType value.
AddBiDiMarks - true adds control characters to the output file to preserve bi-directional layout of the text in the original document.
Document.SaveFormat
Has the Document Changed
The objDocument.Saved property equals True if the document has not changed since it was last saved
This example saves the active document if it's changed since it was last saved.
If (objDocument.Saved = False) Then
objDocument.Save
End If
Saving for the first time
ActiveDocument.SaveAs FileName:="C:\Temp\document.doc"
If you do not specify the folder path then the document is saved in the current folder.
ActiveDocument.SaveAs FileName:="document.doc"
You should always specify the full folder path.
Saving all Open Documents
You can quickly close all the open documents without prompting to save the changes
Documents.Save NoPrompt:=True, _
OriginalFormat:=wdOriginalFormat.wdOriginalDocumentFormat
Checking Properties
You can check to see which properties where set for an activedocument
If (ActiveDocument.EmbedTrueTypeFonts = True) Then
End If
VBA Selecting
The Documents collection starts at 1.
Application.Documents.Item(2)
Application.Documents(2)
Application.Documents("Temp.doc")
Dim objDocument As Document
objDocument = Application.ActiveDocument
objDocument = ActiveDocument
The ActiveDocument is read only and cannot be used to set the active document
Documents("Temp.doc").Activate
WholeStory Method
The WholeStroy method expands a Range or Selection object to include the entire story
The following two lines are equivalent.
objRange.WholeStory
objRange.Expand Unit:=wdUnits.wdStory
Content Property
The content property returns a Range object that represents the main document.
The following two lines are equivalent
ActiveDocument.Content.Select
ActiveDocument.StoryRanges(wdStoryType.wdMainTextStory).Select
VBA Navigating
Selection.MoveRight Unit:=wdUnits.wdCharacter, _
Count:=1
Selection.MoveRight Unit:=wdUnits.wdLine, _
Count:=3
Move to the start of the document
Selection.HomeKey Unit:=wdUnits.wdStory
Move to the end of the document
Selection.EndKey Unit:=wdUnits.wdStory
Move to the start of the line
Selection.HomeKey Unit:=wdUnits.wdLine
Move to the end of the line
Selection.HomeKey Unit:=wdUnits.wdLine
objRange.Collapse Direction:=wdCollapseDirection.wdCollapseStart
Select whole document ??
Selection.HomeKey Unit:=wdUnits.wdStory
Selection.Extend
VBA Edit GoTo
GoTo Method
The Document, Range and Selection objects all have a GoTo method
Selection.GoTo What:=wdGoToItem.wdGoToBookmark
Which:=wdGoToDirection.wdGoToPrevious
Count:=1, _
Name:="Bookmark_Name"
If the What parameter is wdGoToBookmark, wdGoToComment, wdGoToField or wdGoToObject then the Name parameter specifies a name.
This will move to beginning of the line
Selection.GoTo What:=wdGoToItem.wdGoToLine, _
Which:=wdGoToDirectionwdGoToAbsolute, _
Count:=1
To select the line you can use the Expand method
Selection.Expand wdUnits.wdLine
Next and Previous Methods
Note there is no wdGoToCharacter, wdGoToWord or wdGoToSentence constants.
To do this you can use the Next and Previous methods.
This methods applies to a Range, Selection and a Paragraph
objSelection.Next Unit:=wdUnits.wdWord
Count:=1
objRange.Next Unit:=wdUnits.wdCharacter, _
Count:=1
objRange.Next Unit:=wdUnits.wdWord, _
Count:=3
objRange.Next Unit:=wdUnits.wdSentence, _
Count:=2
objParagraph.Next Unit:=wdUnits.wdCharacter
GoToNext and GoToPrevious Methods
The GoToNext and GoToPrevious methods are similar to the GoTo with the Which parameter set to wdGoToNext or wdGoToPrevious and the Count set to 1.
These methods apply to a Range and a Selection
objRange.GoToNext What:=wdGoToItem.wdGoToBookmark
objSelection.GoToPrevious What:=wdGoToItem.wdGoToBookmark
InRange Method
There is also an InRange method which reports whether one range is contained within another.
VBA Find and Replace
link - wordmvp.com/FAQs/General/UsingWildcards.htm
link - gregmaxey.com/word_tip_pages/words_fickle_vba_find_property.html
Find Object
The Find property returns a Find object that you can use to Search a Range.
Selection.Find
ActiveDocument.Content.Find
Properties and Methods
| Font | |
| ClearFormatting | |
| Format | Whether to find formatting in addition to or instead of the Find text ?? |
| Replacement | |
| Execute | |
| Forward | |
| Found | |
| Frame | |
| Highlight | |
| MatchCase | |
| MatchWholeWord | |
| MatchWildcards | |
| NoProofing | |
| ParagraphFormat | |
| Style | |
| Text | |
| Wrap |
Find.Execute
expression.Execute(FindText:="text to find", _
MatchCase:=, _
MatchWholeWord:=, _
MatchWildcards:=, _
MatchSoundsLike:=, _
MatchAllWordForms:=, _
Forward:=, _
Wrap:=wdFindWrap.wdFindContinue, _
Format:=, _
ReplaceWith:=, _
Replace:=, _
MatchKashida:=, _
MatchDiacritics:=, _
MatchAlefHamza:=, _
MatchControl:=)
FindText - Optional Variant. The text to be searched for. Use an empty string ("") to search for formatting only. You can search for special characters by specifying appropriate character codes. For example, "^p" corresponds to a paragraph mark and "^t" corresponds to a tab character. For a list of special characters you can use, see Find and replace text or other items .
MatchCase - Optional Variant. True to specify that the find text be case sensitive. Corresponds to the Match case check box in the Find and Replace dialog box (Edit menu).
MatchWholeWord - Optional Variant. True to have the find operation locate only entire words, not text that's part of a larger word. Corresponds to the Find whole words only check box in the Find and Replace dialog box.
MatchWildcards - Optional Variant. True to have the find text be a special search operator. Corresponds to the Use wildcards check box in the Find and Replace dialog box.
MatchSoundsLike - Optional Variant. True to have the find operation locate words that sound similar to the find text. Corresponds to the Sounds like check box in the Find and Replace dialog box.
MatchAllWordForms - Optional Variant. True to have the find operation locate all forms of the find text (for example, "sit" locates "sitting" and "sat"). Corresponds to the Find all word forms check box in the Find and Replace dialog box.
Forward - Optional Variant. True to search forward (toward the end of the document).
Iterating through all occurrences
You can use the Find object's Found property to iterate through several found items instead of checking the return value of Execute everytime.
Dim objFind As Word.Find
objFind = objRange.Find
objFind.Text = "better"
objFind.MatchWholeWord = True
objFind.Execute
While objFind.Found
objFind.Execute
End While
Looping through paragraphs in a document is very slow
If you are looking for certain text always use Range.Find
Replacing HTML tags
If you want to find and replace special characters you may need to prefix them with a back slash
objFind.Text = "\<b\>"
When the Execute method of the Find object is executed successfully a new Range object is returned
Set objRange = ActiveDocument.Sentences(2)
objRange.Find.Text = "some text"
objRange.Find.Execute
If (objRange.Find.Found = True) Then
objRange.Select
End If
The following example finds the next double-spaced paragraph after the selection.
With Selection.Find
.ClearFormatting
.ParagraphFormat.LineSpacingRule = wdLineSpacing.wdLineSpaceDouble
.Text = ""
.Forward = True
.Wrap = wdFindWrap.wdFindContinue
End With
Selection.Find.Execute
This example finds all double-spaced paragraphs in the active document and replaces the formatting with 1.5-line spacing.
With ActiveDocument.Content.Find
.ClearFormatting
.ParagraphFormat.Space2
.Replacement.ClearFormatting
.Replacement.ParagraphFormat.Space15
.Execute FindText:="", _
ReplaceWith:="", _
Replace:=wdReplace.wdReplaceAll
End With
This example steps through the words in myRange (which spans from the beginning of the active document to the end of the selection) and deletes the word "BetterSolutions" (including the trailing space) wherever it occurs in the range.
Set myRange = ActiveDocument.Range(Start:=0, End:=Selection.End)
For Each aWord In myRange.Words
If aWord.Text = "BetterSolutions" Then
aWord.Delete
End If
Next aWord
Finding
Selection.Find.ClearFormatting ??
With Selection.Find
.Text = "text_to_find"
.Replacement.Text = "replace_with_text"
.Forward = True
.Wrap = wdFindWrap.wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
If Selection.Find.Execute = True Then
End If
Public Sub DoFindReplace(ByVal sFindText As String, _
ByVal sReplaceText As String)
With Selection.Find
.ClearFormatting
.Replacement.ClearFormatting
.Text = sFindText
.Forward = True
.Wrap = wdFindWrap.wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcard = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
Do While Selection.Find.Execute
'keep going until nothing is found
.Execute Replace:=wdReplace.wdReplaceAll
Loop
'free up some memory
ActiveDocument.UndoClear
End Sub
Finding field codes
Selection.Find.ClearFormatting
Selection.Find.Text = "^b" - this is a section break
Selection.Find.Text = "^d"
Selection.Find.Text = "^p" - this is a paragraph mark
Selection.Find.Replacement.ClearFormatting
Selection.Find.Execute Replace:=wdReplace.wdReplaceAll
Selection.Find.Text = "^L"
Selection.TypeText Text:="some text"
Selection.Range.InsertAutoText
Finding symbols
The first thing you need to do is find out both the font and Unicode number of the character you want to search for and /or replace with. If the character was inserted from the Insert + Symbol dialog, its name won't be displayed in the Fonts list on your toolbar, but you can get at the information by selecting the character and running the following macro:
Sub GetCharNoAndFont()
With Dialogs(wdDialogInsertSymbol)
Debug.Print "Font: " & .Font
Debug.Print "Char number " & .CharNum
End With
End Sub
Press Ctrl+G or select View + Immediate Window to see the results.
In the case of the Delta symbol, that will return:
Font: Symbol
Char number -3996
You can now use the following macros to find the next instance of the Delta symbol (if there is one). As you'll see shortly, it is very straightforward, even if you are a complete programming novice, to customise the following macros for your needs.
Sub FindDeltaSymbols()
'Call the main "FindSymbols" macro (below),
'and tell it what character code and font to search for
Call FindSymbols(FindChar:=ChrW(-3996), FindFont:="Symbol")
End Sub
Sub FindSymbols(FindChar As String, FindFont As String)
Dim FoundFont As String, OriginalRange As Range, strFound As Boolean
Application.ScreenUpdating = False
'set range to return to in case symbol not found
Set OriginalRange = Selection.Range
strFound = False
With Selection.Find
.ClearFormatting
.Text = FindChar
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindStop
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
Do While .Execute 'Keep going until nothing found
If Dialogs(wdDialogInsertSymbol).Font = FindFont Then
'If the correct character was found, exit loop
strFound = True
Exit Do
Else
'Otherwise search again
Selection.Collapse wdCollapseEnd
End If
Loop
If Not strFound Then
'if nothing found, search from the beginning of the document
ActiveDocument.Range(0, 0).Select
Do While .Execute
If Dialogs(wdDialogInsertSymbol).Font = FindFont Then
strFound = True
Exit Do
Else
Selection.Collapse wdCollapseEnd
End If
Loop
End If
End With
If Not strFound Then
OriginalRange.Select
End If
Set OriginalRange = Nothing
Application.ScreenUpdating = True
End Sub
To customise it, all you have to do is to use the GetCharNoAndFont() macro again, to find out what chaacter number and font you need to use; and then change the character number and font used in the FindDeltaSymbols() macro to the correct values for the symbol(s) you want to find.
For example, if you want to find the one-eighth symbol, which is listed under "(normal text)" in the insert symbol dialog, insert the symbol into your document, select it, and run the GetCharNoAndFont() macro. This will return:
Font: (normal text)
Char number 8539
So just by changing the reference to "Symbol" in the FindDeltaSymbols() macro to "(normal text)" instead; and the reference to "-3996" to "8539"; we get the following:
Sub FindOneEigthSymbols()
Call FindSymbols(FindChar:=ChrW(8539), FindFont:= "(normal text)")
End Sub
Use this with exactly the same FindSymbols() macro as before.
Finding and replacing symbols
If you want to do a Find and Replace operation, you will need the character numbers and fonts for both the Find and the Replace characters. As before, you can use the GetCharNoAndFont() macro to obtain this information.
You can then customise the following first of the following macros, which calls the second macro, and in this example replaces all instances of the Delta symbol in your document with Beta symbols. To customise it, just change the character numbers and fonts in the ReplaceAllDeltaSymbolsWithBetaSymbols() macro (but leave the ReplaceAllSymbols() macro as it is):
Sub ReplaceAllDeltaSymbolsWithBetaSymbols()
'Call the main "ReplaceAllSymbols" macro (below),
'and tell it which character code and font to search for, and which to replace with
Call ReplaceAllSymbols(FindChar:= ChrW(-3996), FindFont:= "Symbol", _
ReplaceChar:=-3998, ReplaceFont:="Symbol")
End Sub
Sub ReplaceAllSymbols(FindChar As String, FindFont As String, _
ReplaceChar As String, ReplaceFont As String)
Dim FoundFont As String, OriginalRange As Range, strFound As Boolean
Application.ScreenUpdating = False
Set OriginalRange = Selection.Range
'start at beginning of document
ActiveDocument.Range(0, 0).Select
strFound = False
With Selection.Find
.ClearFormatting
.Text = FindChar
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindStop
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
Do While .Execute
'keep searching until nothing found
If Dialogs(wdDialogInsertSymbol).Font = FindFont Then
'Insert the replacement symbol where the found symbol was
Selection.InsertSymbol Font:=ReplaceFont, _
CharacterNumber:=ReplaceChar, Unicode:=True
Else
Selection.Collapse wdCollapseEnd
End If
Loop
End With
OriginalRange.Select
Set OriginalRange = Nothing
Application.ScreenUpdating = True
End Sub
VBA Document Properties
Document Built-in Properties
objDocument.BuiltinDocumentProperties(wdBuiltInProperty.wdPropertyTimeLastPrinted
Document Custom Properties
objDocument.CustomDocumentProperties
DSOFile.dll - Accessing Document Properties without opening the files
Microsoft makes an ActiveX DLL available called dsofile.dll, which allows you to read & write the document properties of an Office file without opening the file in a document editing window.
This includes a template called ListProps.dot that will use dsofile to list all the Office documents in a folder, including whichever of the built-in document properties you want to have.
Download and register dsofile.dll using regsvr32.
Copy the ListProps template into your Word startup folder.
Start Word. A new entry will appear in the Tools menu.
Select the entry. In the dialog that appears, select the properties you want to include in your list, select the folder you want to have listed, and select the template you want to use as the document type for the list.
ListProps then uses dsofile to open each file in turn, get the properties, and puts the list into a table. Works with available properties of Word, Excel & PowerPoint files.
How to use a single VBA procedure to read or write both custom and built-in Document Properties
When you work with Document Properties in code, most people end up with two functions or subroutines, one to write built-in Document Properties and one for custom Document Properties; because in each case the object used to refer to the Document Properties is different - you have to use the CustomDocumentProperties and BuiltinDocumentProperties collection as appropriate. But this can be very inconvenient.
Writing Document Properties
However, you can write a procedure which checks whether the property you want to write the value for is custom or built-in, and then uses the appropriate collection. (Note: If you are not familiar with calling subroutines with arguments, see: How to cut out repetition and write much less code, by using subroutines and functions that take arguments).
Public Sub WriteProp(sPropName As String, sValue As String, _
Optional lType As Long = msoPropertyTypeString)
'In the above declaration, "Optional lType As Long = msoPropertyTypeString" means
'that if the Document Property's Type is Text, we don't need to include the lType argument
'when we call the procedure; but if it's any other Prpperty Type (e.g. date) then we do
Dim bCustom As Boolean
On Error GoTo ErrHandlerWriteProp
'Try to write the value sValue to the custom documentproperties
'If the customdocumentproperty does not exists, an error will occur
'and the code in the errorhandler will run
ActiveDocument.BuiltInDocumentProperties(sPropName).Value = sValue
'Quit this routine
Exit Sub
Proceed:
'We know now that the property is not a builtin documentproperty,
'but a custom documentproperty, so bCustom = True
bCustom = True
Custom:
'Try to set the value for the customproperty sPropName to sValue
'An error will occur if the documentproperty doesn't exist yet
'and the code in the errorhandler will take over
ActiveDocument.CustomDocumentProperties(sPropName).Value = sValue
Exit Sub
AddProp:
'We came here from the errorhandler, so know we know that
'property sPropName is not a built-in property and that there's
'no custom property with this name
'Add it
On Error Resume Next
ActiveDocument.CustomDocumentProperties.Add Name:=sPropName, _
LinkToContent:=False, Type:=msoDocProperties.msoPropertyTypeString, Value:=sValue
If Err Then
'If we still get an error, the value isn't valid for the Property Type
'e,g an invalid date was used
Debug.Print "The Property " & Chr(34) & _
sPropName & Chr(34) & " couldn't be written, because " & _
Chr(34) & sValue & Chr(34) & _
" is not a valid value for the property type"
End If
Exit Sub
ErrHandlerWriteProp:
Select Case Err
Case Else
'Clear the error
Err.Clear
'bCustom is a boolean variable, if the code jumps to this
'errorhandler for the first time, the value for bCustom is False
If Not bCustom Then
'Continue with the code after the label Proceed
Resume Proceed
Else
'The errorhandler was executed before because the value for
'the variable bCustom is True, therefor we know that the
'customdocumentproperty did not exist yet, jump to AddProp,
'where the property will be made
Resume AddProp
End If
End Select
End Sub
We could call the above procedure like this:
Sub Test()
'Author is a built-in property
Call WriteProp(sPropName:="Author", sValue:="William Shakespeare")
'Date Updated is a custom document property
Call WriteProp(sPropName:="Date Updated", sValue:="11 Mar 2001", _
lType:=msoPropertyTypeDate)
End Sub
Reading Document Properties
The same principle can be used when reading Document Properties:
Function ReadProp(sPropName As String) As Variant
Dim bCustom As Boolean
Dim sValue As String
On Error GoTo ErrHandlerReadProp
'Try the built-in properties first
'An error will occur if the property doesn't exist
sValue = ActiveDocument.BuiltInDocumentProperties(sPropName).Value
ReadProp = sValue
Exit Function
ContinueCustom:
bCustom = True
Custom:
sValue = ActiveDocument.CustomDocumentProperties(sPropName).Value
ReadProp = sValue
Exit Function
ErrHandlerReadProp:
Err.Clear
'The boolean bCustom has the value False, if this is the first
'time that the errorhandler is runned
If Not bCustom Then
'Continue to see if the property is a custom documentproperty
Resume ContinueCustom
Else
'The property wasn't found, return an empty string
ReadProp = ""
Exit Function
End If
End Function
We could call the function like this:
Sub Test()
Dim PropVal As String
PropVal = ReadProp("Author")
Debug.Print PropVal
PropVal = ReadProp("Date Completed")
Debug.Print PropVal
End Sub
VBA Document Variables
Document variables are string variables that can be saved into documents or templates.
The Document object has a Variables property that returns a Variables collection containing all variables associated with that document.
Using document variables provides you with a way of saving custom information without actually putting it on the document or using a custom property.
Creating Document Variables
This line of code will create a new variable called "Variable_1" with its string value containing the text "some text".
ActiveDocument.Variables.Add Name:="Variable_1", _
Value:="some text"
This line of code is equivalent but with a variable assigned to the Variables collection
Dim objVariablesCol As Variables
Set objVariablesCol = ActiveDocument.Variables
objVariablesCol.Add Name:="Variable_1", _
Value:=10
Retrieving the Value from a Variable
This line of code will return the string value assigned to the variable called "Variable_1".
Dim sValue As String
sValue = ActiveDocument.Variables("Variable_1").Value
Saving Blank Values
If you save an empty string in your document variables it will be removed automatically.
KB306281
Determining if a Variable exists
If you try to add a variable with the same name as an existing one you will get an error.
There is no Exists property so you have to cycle through them all to determine if the name already exists
Dim objVariable As Variant
For Each objVariable AIn ActiveDocument.Variables
Next objVariable
Instead of looping through the entire collection which could take a while you could use a dedicated function instead.
Remember you should never use the "On Error Resume Next" statement so you need to catch any errors.
If DoesVariable_Exists("Variable_1", ByRef sMyValue) Then
End If
Public Function DoesVariable_Exist(byVal sVariableName As String, _
ByRef sReturn As String) As Boolean
On Error GoTo AnError
sReturn = ActiveDocument.Variables(sVariableName).Value
DoesVariable_Exist = True
Exit Function
AnError:
sReturn = "doesn't exist"
DoesVariableExist = False
End Function
Deleting a Document Variable
This line of code will delete the document variable called "Variable_2" from the active document
ActiveDocument.Variables("Variable_2").Delete
DocVariable Field
Once a document variable has been added the value can be displayed using the DocVariable field.
Document variables can be added to document using the DOCVariable field
The total number of documents currently open
Application.Documents.Count
Current version of Word
Application.Version
Current build of Word
Application.Build
StyleAreaWidth ??
Getting the Position of the cursor
x = Selection.Information(wdInformation.wdHorizontalPositionRelativeToPage)
y = Selection.Information(wdInformation.wdVerticalPositionRelativeToPage)
72pts = 1 inch = 2.54cm
This only works when you are in Page view.
If you are in Normal view it returns the distance from the top margin.
Always set the view to Page view and the magnificationt o 100% before using the Information proeprty to get the cursor position.
Switch to Print Preview
This changes the view to print preview
Application.PrintPreview = True
Define the size of the window on the screen
With Application
.WindowState = wdWindowStateNormal
.Height = 400
.Width = 300
End With
Check the File Exists before opening
With Application.FileSearch
.FileName = "document.doc"
.Lookin = "C:\Temp\"
.Execute
If .FoundFiles.Count > 1 Then
'file exists so it can be opened
End If
End Sub
Is there a document currently open ?
If (Documents.Count >= 1) Then
'a document is currently open
Else
'no document are open
End If
SharePoint
Detect whether SharePoint is present
You can use this code to avoid using SharePoint features in documents that are not part of a SharePoint shared workspace.
If ActiveDocument.SharedWorkspace.Connected then
'SharePoint is present
Else
'SharePoint is not present
End If
Document.CanCheckIn
For this to be true, you must have the document checked out from the SharePoint server.
Document.CheckIn
Checks the document back into the SharePoint server. Use the CanCheckIn property to determine if this can be done or not.
Document.DeleteAllEditableRanges
Useful for resetting the users work area on some document types.
Document.EnforceStyle
Whether to allow manual formatting or force the use of styles only.
Document.GotoEditableRange
Range.GoToEditableRange
Useful for programmatically addressing the available content
Document.SelectAllEditableRanges
Limited uses on some document types for saving the edits elsewhere.
Document.Sync
Updates the local copy of the document from the SharePoint server. Triggers the two sync events after the sync.
View.ShadeEditableRanges
© 2026 Better Solutions Limited. All Rights Reserved. © 2026 Better Solutions Limited TopPrev