Search notes:

Office Object Model: Word - Document

The document object represents an Word document (which is basically a .docx, .docm etc. file).
The document with with the focus (the active document) is returned by application.activeDocument.
document.saveAs2 saves a document.

Methods, properties and events

acceptAllRevisions()
acceptAllRevisionsShown()
activate()
activeTheme
activeThemeDisplayName
activeWindow
activeWritingStyle
addToFavorites()
application
applyDocumentTheme()
applyQuickStyleSet2()
applyTheme()
attachedTemplate
autoFormat()
autoFormatOverride
autoHyphenation
autoSaveOn
background
bibliography
bookmarks
broadcast
buildingBlockInsert() event
builtInDocumentProperties
canCheckin()
characters
chartDataPointTrack
checkConsistency()
checkGrammar()
checkIn()
checkInWithVersion()
checkSpelling()
clickAndTypeParagraphStyle
close()
close() event
closePrintPreview()
coAuthoring
codeName
commandBars
comments
compare()
compatibility
compatibilityMode
computeStatistics()
consecutiveHyphensLimit
container
content
contentControlAfterAdd() event
contentControlBeforeContentUpdate() event
contentControlBeforeDelete() event
contentControlBeforeStoreUpdate() event
contentControlOnEnter() event
contentControlOnExit() event
contentControls
contentTypeProperties
convert()
convertAutoHyphens()
convertNumbersToText()
convertVietDoc()
copyStylesFromTemplate()
countNumberedItems()
createLetterContent()
creator
currentRsid
customDocumentProperties
customXMLParts
dataForm()
defaultTableStyle
defaultTabStop
defaultTargetFrame
deleteAllComments()
deleteAllCommentsShown()
deleteAllEditableRanges()
deleteAllInkAnnotations()
detectLanguage()
disableFeatures
disableFeaturesIntroducedAfter
documentInspectors
documentLibraryVersions
documentTheme
doNotEmbedSystemFonts
downgradeDocument()
email
embedLinguisticData
embedTrueTypeFonts
encryptionProvider
endnotes
endReview()
enforceStyle
envelope
exportAsFixedFormat()
exportAsFixedFormat2()
farEastLineBreakLanguage
farEastLineBreakLevel
fields
final
fitToPages()
followHyperlink()
footnotes
formattingShowClear
formattingShowFilter
formattingShowFont
formattingShowNextLevel
formattingShowNumbering
formattingShowParagraph
formattingShowUserStyleName
formFields
formsDesign
frames
frameset
freezeLayout()
fullName
getCrossReferenceItems()
getLetterContent()
getWorkflowTasks()
getWorkflowTemplates()
goTo()
grammarChecked
grammaticalErrors
gridDistanceHorizontal
gridDistanceVertical
gridOriginFromMargin
gridOriginHorizontal
gridOriginVertical
gridSpaceBetweenHorizontalLines
gridSpaceBetweenVerticalLines
hasPassword
hasVBProject
HTMLDivisions
hyperlinks
hyphenateCaps
hyphenationZone
indexes
inlineShapes
isInAutosave
isMasterDocument
isSubdocument
justificationMode
kerningByAlgorithm
kind
languageDetected
listParagraphs
lists
listTemplates
lockQuickStyleSet
lockServerFile()
lockTheme
mailEnvelope
mailMerge
makeCompatibilityDefault()
manualHyphenation()
merge()
name
new() event
noLineBreakAfter
noLineBreakBefore
oMathBreakBin
oMathBreakSub
oMathFontName
oMathIntSubSupLim
oMathJc
oMathLeftMargin
oMathNarySupSubLim
oMathRightMargin
oMaths
oMathSmallFrac
oMathWrap
openEncoding
open() event
optimizeForWord97
originalDocumentTitle
pageSetup
paragraphs
parent
password
passwordEncryptionAlgorithm
passwordEncryptionFileProperties
passwordEncryptionKeyLength
passwordEncryptionProvider
path
permission
post()
presentIt()
printFormsData
printOut()
printPostScriptOverText
printPreview()
printRevisions
protect()
protectionType
range()
readabilityStatistics
readingLayoutSizeX
readingLayoutSizeY
readingModeLayoutFrozen
readOnly
readOnlyRecommended
redo()
rejectAllRevisions()
rejectAllRevisionsShown()
reload()
reloadAs()
removeDateAndTime
removeDocumentInformation()
removeLockedStyles()
removeNumbers()
removePersonalInformation
removeTheme()
repaginate()
replyWithChanges()
research
resetFormFields()
returnToLastReadPosition()
revisedDocumentTitle
revisions
runAutoMacro()
runLetterWizard()
save()
saveAs2()
saveAsQuickStyleSet()
saved
saveEncoding
saveFormat
saveFormsData
saveSubsetFonts
scripts
sections
select()
selectAllEditableRanges()
selectContentControlsByTag()
selectContentControlsByTitle()
selectLinkedControls()
selectNodes()
selectSingleNode()
selectUnlinkedControls()
sendFax()
sendFaxOverInternet()
sendForReview()
sendMail()
sensitivityLabel
sentences
serverPolicy
setCompatibilityMode()
setDefaultTableStyle()
setLetterContent()
setPasswordEncryptionOptions()
shapes
showGrammaticalErrors
showSpellingErrors
signatures
smartDocument
snapToGrid
snapToShapes
spellingChecked
spellingErrors
storyRanges
styles
styleSheets
styleSortMethod
subdocuments
sync
sync() event
tables
tablesOfAuthorities
tablesOfAuthoritiesCategories
tablesOfContents
tablesOfFigures
textEncoding
textLineEnding
toggleFormsDesign()
trackFormatting
trackMoves
trackRevisions
transformDocument()
type
undo()
undoClear()
unprotect()
updateStyles()
updateStylesOnOpen
useMathDefaults
userControl
variables create named variables and assign values to them.
vBASigned
vBProject
viewCode()
viewPropertyBrowser()
webOptions
webPagePreview()
windows
wordOpenXML
words
writePassword
writeReserved
XMLAfterInsert() event
XMLBeforeDelete() event
XMLSaveThroughXSLT
XMLSchemaReferences
XMLShowAdvancedErrors
XMLUseXSLTWhenSaving

documents.add

documents.add creates a new Word document.
The following example creates three documents, writes some silly text into them and sets the newly created documents' saved property to true so that the documents can be closed without being prompted for confirmation if they need to be saved.
'
'  ..\..\..\runVBAFilesInOffice.vbs -word add -c add
'

sub add()

    activeDocument.saved = true

    dim doc(3) as document

    for i = 1 to 3 
        set doc(i) = documents.add()
    next i

    for i = 1 to 3 

        call doc(i).select

        call selection.moveLeft(unit:=wdCharacter, count:=1, extend:=wdExtend)

        call selection.typeText(i)
        call selection.moveLeft(unit:=wdCharacter, count:=1, extend:=wdExtend)

        selection.font.name = "Courier New"
        selection.font.size =  100


    next i

    for i = 1 to 3 
        doc(i).saved = true
    next i


end sub
Github repository about-MS-Office-object-model, path: /Word/Documents/add.bas

document_open

document_open is an event that is triggered when a document is opened.
In the event procedure, the me keyword refers to the document that is being opened.
option explicit

sub document_open()
    msgBox "document " & me.name & " was opened"
end sub 
Github repository about-MS-Office-object-model, path: /Word/Document/document_open.bas

path

….path returns the directory where the respective document is stored.
Compare with application.path.

variables

The variables property of a document allows to create named variables and assign values to them.
The following code snippet creates a new document and adds two variables, num and txt.
It then adds two fields whose type is wdFieldDocVariable, to dynamically show the values of the variables within the document.
option explicit

sub main() ' {

    dim doc            as document
    dim fldNum, fldTxt as field

    set doc = documents.add

    doc.variables.add "num",  42
    doc.variables.add "txt", "Hello world"

    doc.content.insertAfter "Number = "

    set fldNum = doc.fields.add(endOfDocument(doc), wdFieldDocVariable, "num")

    doc.content.insertAfter chr(13)
    doc.content.insertAfter "Text = "
    set fldTxt = doc.fields.add(endOfDocument(doc), wdFieldDocVariable, "txt")

    fldNum.showCodes = false
    fldtxt.showCodes = false

end sub ' }

function endOfDocument(doc as document) as range ' {
  '
  ' Return the end of the document as a range.
  ' Not really sure if this is the most efficient and
  ' preferred way to do that.
  '

    set endOfDocument = doc.content
    endOfDocument.collapse wdCollapseEnd

end function ' }
Github repository about-MS-Office-object-model, path: /Word/Document/variables/field.bas
When run, a document like the following is produced:

mailMerge

Returns a document's MailMerge object (which is present whether or not a document is set up for mail merge operations).

See also

In order to insert dynamic text (such as current page number or date) into a Word document, fields might be used.
The PageSetup object controls a document's pages attribute such as paper size, margins, orientation etc.
Word Object Model

Index