Home

 

Joy E. Daniels     ♦ Programming Reporting Support

Word VBA Code

 

Services
Clients
Products
VBA Code
Shortcut Keys
Contact

Description

VBA Code

Message Box

'==Message Box with line break:

MsgBox(“This is the first line,” & vbCrLf & _

“and this is the second line.”)

 

'==Message Box with Yes/No:

Dim strAnswer as String

strAnswer = MsgBox("Display in Print Layout view?", vbYesNo, _

"VIEW SELECTION")

If strAnswer = vbYes Then

ActiveWindow.View.Type = wdPrintView

Else

ActiveWindow.View.Type = wdNormalView

End If

 

'==Prompt user for text:

Dim strName as String

strName = InputBox("Enter your name:", "APPLICANT NAME")

Selection.TypeText Text:=strName

Display

'==Display or hide a toolbar:

If CommandBars("Web").Visible = False Then

CommandBars("Web").Visible = True

Else

CommandBars("Web").Visible = False

End If

 

'==Show built-in dialog box with specific tab displayed:

With Dialogs(wdDialogFilePageSetup)

.DefaultTab = wdDialogFilePageSetupTabPaperSource

.Show

End With

 

'==Turn Spelling and Grammar wavy lines on or off:

If ActiveDocument.ShowGrammaticalErrors = True Then

ActiveDocument.ShowSpellingErrors = False

ActiveDocument.ShowGrammaticalErrors = False

Else

If ActiveDocument.ShowSpellingErrors = True Then

ActiveDocument.ShowSpellingErrors = False

ActiveDocument.ShowGrammaticalErrors = False

Else

ActiveDocument.ShowSpellingErrors = True

ActiveDocument.ShowGrammaticalErrors = True

End If

End If

Testing

'==Whether insertion point is in a table:

If Selection.Information(wdWithInTable) = True Then

Selection.Cells.Shading.BackgroundPatternColor = _

wdColorGold

Else

MsgBox("Click inside the table, then run macro again.")

End If

 

'==Whether a document window is open:

If Documents.Count < 1 Then

Documents.Add Template:="Normal", NewTemplate:=False

End If

Updating Fields

'==Update fields in document and in headers/footers:

Dim sec As Section

ActiveDocument.Fields.Update

For Each sec In ActiveDocument.Sections

sec.Headers(wdHeaderFooterPrimary).Range.Fields.Update

sec.Headers(wdHeaderFooterFirstPage).Range.Fields.Update

sec.Footers(wdHeaderFooterPrimary).Range.Fields.Update

sec.Footers(wdHeaderFooterFirstPage).Range.Fields.Update

Next

 

'==Update Table of Contents:

Dim toc As TableOfContents

For Each toc In ActiveDocument.TablesOfContents

toc.Update

Next

Miscellaneous

'==Insert AutoText and its formatting:

ActiveDocument.AttachedTemplate.AutoTextEntries("Confi-

dential").Insert Where:=Selection.Range, RichText:=True

 

'==Go to a bookmark in a document:

If ActiveDocument.Bookmarks.Exists("ZIPcode") = True Then

Selection.GoTo What:=wdGoToBookmark, Name:="ZIPcode"

Else

MsgBox(“No ZIPcode bookmark exists in this document.”)

End If