Word-VBA Code Samples for Newbies & Others

by JoJo Zawawi


This code was written for Word 97 and worked fine for Word 2000.
No guarantees are given for any later versions of Word,
but most of this code will likely still be valid.

« A »

Array, ReDim an Array:
ReDim arrArrayName(intNumberNames)

Array, Sort an Array:
WordBasic.SortArray (arrArrayName())

« B »

Backspace:
Selection.TypeBackspace

Bookmark, Add:
With ActiveDocument.Bookmarks
   .Add Range:=Selection.Range, Name:="Name"
   .DefaultSorting = wdSortByName
   .ShowHidden = False
End With

Bookmark, Count # of Bookmarks in Document:
Dim intNumBookmarks as Integer
intNumBookmarks = ActiveDocument.Bookmarks.Count

Bookmark, Delete:
ActiveDocument.Bookmarks("BookmarkName").Delete

Bookmark, Exists (Does It Exist?):
If ActiveDocument.Bookmarks.Exists("BookmarkName") = True then
   'Do something, i.e.,:
   ActiveDocument.Bookmarks("BookmarkName").Select
   Selection.TypeText Text:="Hello"
End If

Bookmark, Go to Bookmark:
(This method does not work with bookmarks in Headers/Footers)

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

Bookmark, Select a Bookmark:
(This method works when using bookmarks in Headers/Footers)

ActiveDocument.Bookmarks("BookmarkName").Select

Bookmark, Insert Text Using Range (Change Content of Range):
(This method works when using bookmarks in Headers/Footers)

ActiveDocument.Bookmarks("BookmarkName").Range.Text="Text"

Bookmark, Insert Text Using Range (Add After Range):
(This method works when using bookmarks in Headers/Footers)

ActiveDocument.Bookmarks("BookmarkName").Range.InsertAfter _
   "Text"

Bookmark, Go to a Bookmark, replace the text that's contained
in the Bookmark, and still have the text bookmarked:

Selection.GoTo What:=wdGoToBookmark, Name:="BookmarkName"
Selection.Delete Unit:=wdCharacter, Count:=1
Selection.InsertAfter "This is the new text"
ActiveDocument.Bookmarks.Add Range:=Selection.Range, _
   Name:="BookmarkName"

Bookmark, Replace Text of a Bookmark in document2 With the
Text of a Bookmark in document1:
Note that both documents must be open when the macro is run.

Documents("c:\temp\document2.doc").Bookmarks("doc2BookmarkName").Range.Text = _
   Documents("c:\temp\document1.doc").Bookmarks("doc1BookmarkName").Range.Text
Alternate Code:
Documents("c:\temp\document2.doc").Bookmarks(1).Range.Text = _
   Documents("c:\temp\document1.doc").Bookmarks(4).Range.Text
where the text of the 4th bookmark in document1 is replacing the text
of the 1st bookmark in document2.

Bookmark, Turn Off View Bookmarks:
ActiveWindow.View.ShowBookmarks = False

« C »

Call, Run a Macro That's in Another Template:
Application.Run "[TemplateName].[ModuleName].[MacroName]
Example: Application.Run "Normal.NewMacros.Macro1"
Example: Application.Run "Normal.Module1.Macro2"

Call, Run a Macro That's Within the Same Template:
Application.Run MacroName:="[MacroName]"

Caption, Load an Array Element Into an Option Box Caption:
opt1.Caption = arrArrayName(0)

CHR (Character) Function:
Here are some of the more commonly used ASCII codes:
Chr(9) = tab
Chr(11) = manual line break (shift-enter)
Chr(12) = manual page break
Chr(13) = vbCrLf (return)
Chr(14) = column break
Chr(30) = non-breaking hyphen
Chr(31) = optional hyphen
Chr(32) = space
Chr(34) = quotation mark
Chr(160) = nonbreaking space
For more, look up ASCII character codes in the appendix of most
computer books. See also "Chr$" under VBA Help.
USAGE EXAMPLE: Selection.TypeText text:=Chr(11)

ComboBox, Add Array Items to Combo Box:
For i = 1 to 18   '18 elements in array
   cbxComboBoxName.AddItem arrArrayName(i)
Next i

ComboBox, Set First Value to Show in Combo Box From an Array:
cbxComboBoxName.Value = arrArrayName(0)
   '[(1) if Option Base 1]

Constant, Declare a Constant:
Const strIniFile as String = _
   "C:\Temp\MyFile.txt"

Copy Entire Document:
Selection.HomeKey Unit:=wdStory
Selection.Extend

Copy:
Selection.Copy

« D »

Delete:
Selection.Delete Unit:=wdCharacter, Count:=1

Directory, Exists:
This particular code determines whether your computer has a C:\Windows\Temp
directory (you are running Windows) or a C:\WINNT\Temp directory (you are
running NT); of course, you can use this function to determine whether any
directory exists (for example, if SomeDir exists, great; elseif SomeDir
doesn't exist, then create it, etc.)

Dim strTempDirPath as String
Const strNTTempDirPath as String = "C:\WINNT\Temp"
Const strWindowsTempDirPath as String = "C:\Windows\Temp"
If Dir(strNTTempDirPath, vbDirectory) <> "" Then
   StrTempDirPath = strNTTempDirPath
   MsgBox ("The directory " + strTempDirPath + " exists.")
ElseIf Dir(strWindowsTempDirPath, vbDirectory) <> "" Then
   StrTempDirPath = strWindowsTempDirPath
   MsgBox ("The directory " + strTempDirPath + " exists.")
End If

Document Variable, Set (Create) a Document Variable
(NOTE: This refers to a Word Document Variable, as opposed to
a Variable used in computer programming):

Dim aVar as Variant
Dim iNum as Integer
Dim DocumentType as Variant
For Each aVar In ActiveDocument.Variables
   If aVar.Name = "DocumentType" Then iNum = aVar.Index
Next aVar
If iNum = 0 Then
   ActiveDocument.Variables.Add Name:="DocumentType", _
      Value:="Letter"
Else
   ActiveDocument.Variables("DocumentType").Value = "Letter"
End If

Document Variable, Create Draft# Doc Variable if Does Not Yet Exist
& Set Document, Draft # to 1 (NOTE: This refers to a Word Document
Variable, as opposed to a Variable used in computer programming):

Dim DraftNumber as String
Dim aVar as Variant
Dim iNum as Integer
For Each aVar In ActiveDocument.Variables
   If aVar.Name = "DraftNumber" Then iNum = aVar.Index
Next aVar
If iNum = 0 Then
   ActiveDocument.Variables.Add Name:="DraftNumber", Value:=1
Else
   ActiveDocument.Variables(iNum).Value = 1
End If

Document Variable, What is the Current DocumentType Document Variable
Set To? (NOTE: This refers to a Word Document Variable, as opposed to
a Variable used in computer programming)

MsgBox ("The document variable is set to type: " & _
   ActiveDocument.Variables("DocumentType").Value)

Document Variable, Check Document Variable Value (NOTE: This refers
to a Word Document Variable, as opposed to a Variable used in computer
programming):

Dim strDocType as String
strDocType = _
   ActiveDocument.Variables("[DocumentVariableName]")

Document, Go to Start of Document:
Selection.HomeKey Unit:=wdStory

Document, Go to End of Document:
Selection.EndKey Unit:=wdStory

Document, New, Create a New Document from Another
Document (Template, Form Document, etc.):

Documents.Add Template:="C:\Forms\FormDoc.doc", _
   NewTemplate:=False

Document, Protect Document:
ActiveDocument.Protect Password:="[password]", _
   NoReset:=False, Type:=wdAllowOnlyFormFields

Document, Save Document:
ActiveDocument.Save

Document, SaveAs
ActiveDocument.SaveAs ("C:\Temp\MyFile.doc")

Document, SaveAs (with all the junk):
ActiveDocument.SaveAs FileName:="C:\Temp\MyFile.doc",
   FileFormat:=wdFormatDocument, LockComments:=False, _
   Password:="", AddToRecentFiles:=True, WritePassword:="", _
   ReadOnlyRecommended:=False, EmbedTrueTypeFonts:=False, _
   SaveNativePictureFormat:=False, SaveFormsData:=False, _
   SaveAsAOCELetter:=False

Document, Unprotect Document:
If ActiveDocument.ProtectionType := wdNoProtection Then
   ActiveDocument.Unprotect Password:="readonly"
End If

« E »

Extend, Turn Off Extend Mode:
Selection.ExtendMode = False

« F »

Field Code, Lock Field Code:
Selection.Fields.Locked = True

Field Code, Insert SEQ Field Code:
Selection.Fields.Add Range:=Selection.Range, _
   Type:=wdFieldEmpty, Text:="SEQ name \n", _
   PreserveFormatting:=True

Field Code, Reset SEQ Field Code to Zero (Restart #ing):
Selection.Fields.Add Range:=Selection.Range, _
   Type:=wdFieldEmpty, Text:="SEQ name \r0 \h ", _
   PreserveFormatting:=True

Field Code, Sequence Numbering Field Codes With Sub-Levels:
Level 1:
Selection.Fields.Add Range:=Selection.Range, Type:=wdFieldEmpty, _
   Text:="SEQ \L1 \*arabic \c \* MERGEFORMAT", _
   PreserveFormatting:=True
Level 2:
Selection.Fields.Add Range:=Selection.Range, Type:=wdFieldEmpty, _
   Text:="SEQ \L2 \*alphabetic \c \* MERGEFORMAT", _
   PreserveFormatting:=True
(etc.)

Field Code, SEQ#, Reset #s to 0:
Selection.Fields.Add _
   Range:=Selection.Range, Type:=wdFieldEmpty, _
   Text:="SEQ L1 \r0 \h", PreserveFormatting:=True
Selection.Fields.Add _
   Range:=Selection.Range, Type:=wdFieldEmpty, _
   Text:="SEQ L2 \r0 \h", PreserveFormatting:=True

Field Code, Unlock Field Code:
Selection.Fields.Locked = False

Field Code, Update Field Code:
Selection.Fields.Update

Field Code, View Field Codes:
ActiveWindow.View.ShowFieldCodes = True

Field Code, View Field Codes (with all the junk):
ActiveWindow.View.ShowFieldCodes = _
   Not ActiveWindow.View.ShowFieldCodes
With ActiveWindow
   With .View
      .ShowFieldCodes = True
   End With
End With

Find:
Selection.Find.ClearFormatting
With Selection.Find
   .Text = "xxx"
   .Replacement.Text = ""
   .Forward = True
   .Wrap = wdFindContinue
   .Format = False
   .MatchCase = False
   .MatchWholeWord = False
   .MatchWildcards = False
   .MatchSoundsLike = False
   .MatchAllWordForms = False
End With
Selection.Find.Execute

Find, Was It Found? (version 1)
If Selection.Find.Found = True Then
   'blah blah blah
End If

Find, Was It Found? (version 2, thanks to Shawn Wilson)
If Selection.Find.Execute Then
   'blah blah blah
End If

Find, Field Code:
Selection.Find.ClearFormatting
With Selection.Find
   .Text = "^d"
... [all the other junk, i.e., direction, etc.]
End With

Find, Paragraph Mark (Real Paragraph, Not the Symbol):
Selection.Find.ClearFormatting
With Selection.Find
   .Text = "^p"
   .Forward = True
   .Wrap = wdFindStop
End With
Selection.Find.Execute

Find, Replace:
Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
With Selection.Find
   .Text = "xxx"
   .Replacement.Text = "yyy"
   .Forward = True
   .Wrap = wdFindContinue
   .Format = False
   .MatchCase = False
   .MatchWholeWord = False
   .MatchWildcards = False
   .MatchSoundsLike = False
   .MatchAllWordForms = False
End With
Selection.Find.Execute Replace:=wdReplaceAll

Find, Replace Hard Returns With Manual Line Breaks
Within Selected Text:

Selection.Extend
Selection.Find.ClearFormatting
With Selection.Find
   .Text = "^l"          'L not 1
   .Forward = False
   .Wrap = wdFindStop
End With
Selection.Find.Execute
Selection.MoveRight Unit:=wdCharacter, Count:=1, Extend:=wdExtend
Selection.Find.ClearFormatting
With Selection.Find
   .Text = "^p"
   .Replacement.Text = "^l"       'L not 1
   .Forward = True
   .Wrap = wdFindStop
End With
Selection.Find.Execute Replace:=wdReplaceAll
Selection.MoveRight Unit:=wdCharacter, Count:=1

Font, Set Font Size:
Selection.Font.Size = 12

Font:
With Selection.Font
   .Hidden = True
   .ColorIndex = wdRed [or] wdAuto
End With

Footer, View Footer:
ActiveWindow.ActivePane.View.SeekView = _
   wdSeekCurrentPageFooter

Form, Hide a Form:
frmFormName.Hide

Form, Load & Show a Form:
Load frmFormName
frmFormName.Show

« G »

GoTo, Go to Bookmark:
(This method not suggested for use with bookmarks in Headers/Footers;
see "Bookmarks" entries under "B")

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

GoTo, Go to Page 1
Selection.GoTo What:=wdGoToPage, Which:=wdGoToNext, Name:="1"

« H »

Header, View Current Page Header:
ActiveWindow.ActivePane.View.SeekView = _
   wdSeekCurrentPageHeader

Header, View Header (with all the junk):
If ActiveWindow.View.SplitSpecial := wdPaneNone Then
   ActiveWindow.Panes(2).Close
End If
If ActiveWindow.ActivePane.View.Type = wdNormalView Or _
   ActiveWindow.ActivePane.View.Type = wdOutlineView Or _
   ActiveWindow.ActivePane.View.Type = wdMasterView Then _
   ActiveWindow.ActivePane.View.Type = wdPageView
End If
ActiveWindow.ActivePane.View.SeekView = wdSeekCurrentPageHeader

« I »

IF Test:
If [condition] Then
   [Do Something]
ElseIf [another condition] Then
   [Do Something Else]
Else [another condition] Then
   [Do Something Else]
End If

Indent, Set Left Indent:
Selection.ParagraphFormat.LeftIndent = InchesToPoints(3.75)

Indent, Set Right Indent:
Selection.ParagraphFormat.RightIndent = InchesToPoints(1)

InputBox, Get & Use Data From an Input Box:
Dim strData as String
strData = InputBox("What is the data?")
MsgBox (strData)

Insert After:
Selection.InsertAfter "xxx"

Insert an Underlined Tab:
Selection.Font.Underline = wdUnderlineSingle
Selection.TypeText Text:=vbTab
Selection.Font.Underline = wdUnderlineNone

Insert AutoText:
Selection.TypeText Text:="a3"
Selection.Range.InsertAutoText

Insert Date Code (Month Only):
Selection.Fields.Add Range:=Selection.Range, _
   Type:=wdFieldEmpty, Text:="DATE \@ ""MMMM""", _
   PreserveFormatting:=True

Insert Date Code (Year Only):
Selection.Fields.Add Range:=Selection.Range, _
   Type:=wdFieldEmpty, Text:="DATE \@ ""yyyy""", _
   PreserveFormatting:=True

Insert File:
Selection.InsertFile ("C:\Docs\Something.doc")

Insert Page Break:
Selection.InsertBreak Type:=wdPageBreak

Insert Paragraph Symbol:
Selection.TypeText Text:=Chr$(182)

Insert Section Symbol:
Selection.TypeText Text:=Chr$(167)

Insert SEQ# Field Code:
Selection.Fields.Add Range:=Selection.Range, _
   Type:=wdFieldEmpty, Text:="SEQ name \n", _
   PreserveFormatting:=True

Insert Text in Upper Case:
Selection.TypeText Text:=UCase(strStuff)   OR
Selection.TypeText Text:=UCase(cbxSigBlockAnotherName.Value)

Insert Symbol:
Selection.InsertSymbol CharacterNumber:=8212, _
   Unicode:=True, Bias:=0
   (This happens to be the symbol for an "M-dash")

Insert Tab:
Selection.TypeText Text:=vbTab

Insert Text (replaces selection if anything is selected):
Selection.TypeText Text:=txtStuff.text [or] "Hello" [or]
   strText

Insert Text After Position of Cursor (does not replace
selection; appends text to end of selection:

Selection.InsertAfter txtStuff.text [or] "Hello" [or] strText

Insert Various Characters:
Selection.TypeText Text:=vbTab   'Tab
Selection.TypeText Text:=vbCrLf  'Para Return

Insert, Type Paragraph:
Selection.TypeParagraph

« J »

« K »

« L »

Line, Beginning of Line:
Selection.HomeKey Unit:=wdLine

Line, End of Line:
Selection.EndKey Unit:=wdLine

Line Spacing, Set Line Spacing to Exactly:
Selection.ParagraphFormat.LineSpacingRule = wdLineSpaceExactly
Selection.ParagraphFormat.LineSpacing = 12
   OR
With Selection.ParagraphFormat
   .LineSpacingRule = wdLineSpaceExactly
   .LineSpacing = 12
End With

Loop: Do...Loop:
Do While intCounter < 10
   intCounter = intCounter + 1
   Selection.TypeText Text:="Howdy"
Loop

Loop: Do Until End of Document
Do Until ActiveDocument.Bookmarks("\Sel") = _
   ActiveDocument.Bookmarks("\EndOfDoc")
   '(Do something)
Loop

Loop: Do a Search, Then Execute Some Other Commands
Inside a "Do Until End of Document" Loop (version 1):

Do Until ActiveDocument.Bookmarks("\Sel") = _
   ActiveDocument.Bookmarks("\EndOfDoc")
      Selection.Find.ClearFormatting
      With Selection.Find
         .Text = "Howdy!"
         .Forward = True
         .Wrap = wdFindStop
         .Format = False
         .MatchCase = False
         .MatchWholeWord = False
         .MatchWildcards = False
         .MatchSoundsLike = False
         .MatchAllWordForms = False
      End With
      Selection.Find.Execute

      If Selection.Find.Found = True Then
         'Do something within the found text
      Else
         Exit Do
      End If
   Loop

Loop: Do a Search, Then Execute Some Other Commands Inside
a "Do Until End of Document" Loop (version 2, thanks to Shawn Wilson):

Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
With Selection.Find
   .Text = "Something"
   .ReplacementText = ""
   .Forward = True
   .Wrap = wdFindStop
   .Format = False
   .MatchCase = False
   .MatchWholeWord = False
   .MatchWildcards = False
   .MatchSoundsLike = False
   .MatchAllWordForms = False
End With
Do While Selection.Find.Execute
   'Do something within the found text
Loop

Loop: Do a Search, Then Execute Some Other Commands Inside a
"Do Until End of Document" Loop (version 3, thanks to Shawn Wilson):

Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
With Selection.Find
   .Text = "Something"
   .ReplacementText = ""
   .Forward = True
   .Wrap = wdFindStop
   .Format = False
   .MatchCase = False
   .MatchWholeWord = False
   .MatchWildcards = False
   .MatchSoundsLike = False
   .MatchAllWordForms = False
End With
While Selection.Find.Execute
   'Do something within the found text
Wend

« M »

Macro, Run a Macro That's in Another Template:
Application.Run "[TemplateName].[ModuleName].[MacroName]
Example: Application.Run "Normal.NewMacros.Macro1"
Example: Application.Run "Normal.Module1.Macro2"

Macro, Run a Macro That's Within the Same Template:
Application.Run MacroName:="[MacroName]"

Move Right, 1 Cell in a Table:
Selection.MoveRight Unit:=wdCell

Move Right, a Few Cells in a Table:
Selection.MoveRight Unit:=wdCell, Count:=3

Move Right, With Extend On:
Selection.MoveRight Unit:=wdCharacter, Count:=1, Extend:=wdExtend

Move Right:
Selection.MoveRight Unit:=wdCharacter, Count:=1

Move Up One Paragraph:
Selection.MoveUp Unit:=wdParagraph, Count:=1

MsgBox Result:
Dim intMsgBoxResult as Integer
intMsgBoxResult = MsgBox("Are you alive", vbYesNo + _
   vbQuestion, "Current Status")

MsgBox, Use the MsgBox Result:
Dim intMsgBoxResult as Integer
If intMsgBoxResult = vbYes Then
   'Do something
End If

« N »

Number, Is Selected Text a Number? (IsNumeric function)
Dim strSelText As String
strSelText = Selection.Text
If IsNumeric(strSelText) = True Then
    MsgBox ("It's a number!")
Else
    MsgBox ("It's not a number!")
End If

Number of Pages, Determine # Pages in Document:
Dim varNumberPages as Variant
varNumberPages = _
   ActiveDocument.Content.Information(wdActiveEndAdjustedPageNumber)

« O »

« P »

Paragraph, Justify Paragraph:
Selection.ParagraphFormat.Alignment = wdAlignParagraphLeft

Paragraph, KeepLinesTogether:
Selection.ParagraphFormat.KeepTogether = True

Paragraph, KeepWithNext:
Selection.ParagraphFormat.KeepWithNext = True

Paragraph, Space After:
Selection.ParagraphFormat.SpaceAfter = 12

Paragraph, Space Before:
Selection.ParagraphFormat.SpaceBefore = 0

Paragraph, WidowOn:
Selection.ParagraphFormat.WidowControl = True

Paste:
Selection.Paste

Properties, Set Properties On the Fly:
cmdOK.Visible = False
cmdOK.Enabled = False
optOther.Value = False
txtOther.Text = ""

« Q »

« R »

Run a Macro That's in Another Template:
Application.Run "[TemplateName].[ModuleName].[MacroName]
Example: Application.Run "Normal.NewMacros.Macro1"
Example: Application.Run "Normal.Module1.Macro2"

Run a Macro That's Within the Same Template:
Application.Run MacroName:="[MacroName]"

« S »

Select, All (Entire Document):
Selection.WholeStory

Select, Entire Line:
Selection.EndKey Unit:=wdLine, Extend:=wdExtend

Select, Entire Line (Except Paragraph Mark):
Selection.EndKey Unit:=wdLine, Extend:=wdExtend
Selection.MoveLeft Unit:=wdCharacter, Count:=1, Extend:=wdExtend

Select, Text, Using Extend:
Selection.EndKey Unit:=wdLine, Extend:=wdExtend
Selection.HomeKey Unit:=wdLine
Selection.MoveRight Unit:=wdCharacter, Count:=2, _
   Extend:=wdExtend

Smart Cut & Paste Off:
Options.SmartCutPaste = False

Smart Quotes, Turn On "Smart Quotes As-You-Type":
With Options
   .AutoFormatAsYouTypeReplaceQuotes = True
End With

Start of Line:
Selection.HomeKey Unit:=wdLine

Style, Copy Style Using Organizer:
Dim strThisDocument as String
strThisDocument = ActiveDocument.FullName
Application.OrganizerCopy Source:= _
   "C:\Program Files\Microsoft Office\Templates\Normal.dot", _
   Destination:=strThisDocument, Name:="[StyleName]", _
   Object:=wdOrganizerObjectStyles

Style, Set a Style:
Selection.Style = ActiveDocument.Styles("[StyleName]")

« T »

Table of Contents, Update Page Numbers Only:
ActiveDocument.TablesOfContents(1).UpdatePageNumbers

Table, Go to 1st Table in Document:
Selection.GoTo What:=wdGoToTable, Which:=wdGoToFirst, _
   Count:=1, Name:=""

Table, Show Table Gridlines:
ActiveWindow.View.TableGridlines = True

Table, Take Borders Off Table:
With Selection.Cells
   .Borders(wdBorderLeft).LineStyle = wdLineStyleNone
   With .Borders(wdBorderRight)
      .LineStyle = wdLineStyleSingle
      .LineWidth = wdLineWidth075pt
      .ColorIndex = wdAuto
   End With
   With .Borders(wdBorderTop)
      .LineStyle = wdLineStyleSingle
      .LineWidth = wdLineWidth075pt
      .ColorIndex = wdAuto
   End With
   With .Borders(wdBorderBottom)
      .LineStyle = wdLineStyleSingle
      .LineWidth = wdLineWidth075pt
      .ColorIndex = wdAuto
   End With
   .Borders.Shadow = False
End With
With Options
   .DefaultBorderLineStyle = wdLineStyleSingle
   .DefaultBorderLineWidth = wdLineWidth050pt
   .DefaultBorderColorIndex = wdAuto
End With

Table, Total the Numbers
Selection.InsertFormula Formula:="=SUM(ABOVE)", _
   NumberFormat:="#,##0.00"

Tabs, Clear All:
Selection.ParagraphFormat.TabStops.ClearAll
ActiveDocument.DefaultTabStop = InchesToPoints(0.5)

Tabs, Tab Stop, Add:
Selection.ParagraphFormat.TabStops.Add _
   Position:=InchesToPoints(6.63), _
   Alignment:=wdAlignTabRight, Leader:=wdTabLeaderSpaces

TextBox, Is There Something in a Text Box:
If txtStuff.Text := "" Then
   MsgBox("There is nothing in the text box")
End If

Text File, Open, Write to & Close:
Open "C:\Temp\MyFile.txt" For Output As #1
Write #1, "This is some text."
Close #1

Text File, Open, Read Data Into Variables & Close:
This example assumes that "C:\Temp\MyFile.txt" is a text file with a few
lines of text in it, each line containing a string in quotations and a
number separated by a comma. For example:
    "Howdy Doodie", 12345 
    "Good Morning", 67890

Dim MyString, MyNumber
Open "C:\Temp\MyFile.txt" For Input As #1
Do While Not EOF(1)                'Loop until end of file
Input #1, MyString, MyNumber       'Read data into two variables
MsgBox (MyString & " " & MyNumber) 'Show variable contents in message box
Loop
Close #1

« U »

Underline, Turn On Single Underline:
Selection.Font.Underline = wdUnderlineSingle

Underline, Turn Off Single Underline:
Selection.Font.Underline = wdUnderlineNone

Unload Forms - Unload All of Them (i.e., at End of Program):
Dim frm as Userform
For Each frm in Userforms
   Unload frm
Next frm

User Info, Set User Initials in Tools, User Info:
Application.UserInitials = "[initials]"   OR
(If getting user initials from an .ini file:)
Application.UserInitials = System.PrivateProfileString(strIniFile, _
   "Initials", strUserName)      OR
Application.UserInitials = strUserInitials

User Info, Set User Name in Tools, User Info:
Application.UserName = "[UserName]"      OR
Application.UserName = cbxUserName.Value   OR
Application.UserName = strUserName

« V »

Value, Get Value of a Number From a String:
intNumber = Val(txtNumber.Text)

Variable, Declare:
Note: "Dim" stands for "Dimension"
Dim [VariableName] as [TypeOfVariable]
Example: Dim strName as String
There are many kinds of Variables and ways to declare them.
Look under VBA "Help" for a listing and explanation.

View, Bookmarks:
ActiveWindow.View.ShowBookmarks = True

View, Current Page Header:
ActiveWindow.ActivePane.View.SeekView = _
   wdSeekCurrentPageHeader

View, Field Codes (with all the junk):
ActiveWindow.View.ShowFieldCodes = _
   Not ActiveWindow.View.ShowFieldCodes
With ActiveWindow
   With .View
      .ShowFieldCodes = True
   End With
End With

View, Field Codes:
ActiveWindow.View.ShowFieldCodes = True

View, Footer:
ActiveWindow.ActivePane.View.SeekView = _
   wdSeekCurrentPageFooter

View, Header:
ActiveWindow.ActivePane.View.SeekView = wdSeekCurrentPageHeader

View, Header (with all the junk):
If ActiveWindow.View.SplitSpecial := wdPaneNone Then
   ActiveWindow.Panes(2).Close
End If
If ActiveWindow.ActivePane.View.Type = wdNormalView Or _
   ActiveWindow.ActivePane.View.Type = wdOutlineView Or _
   ActiveWindow.ActivePane.View.Type = wdMasterView Then _
   ActiveWindow.ActivePane.View.Type = wdPageView
End If
ActiveWindow.ActivePane.View.SeekView = wdSeekCurrentPageHeader

View, Main View (Close Header or Footer:)
ActiveWindow.ActivePane.View.SeekView = wdSeekMainDocument

View, Options:
Application.DisplayStatusBar = True
With ActiveWindow
   .DisplayHorizontalScrollBar = True
   .DisplayVerticalScrollBar = True
   .DisplayVerticalRuler = True
   .DisplayScreenTips = True
   With .View
      .ShowAnimation = True
      .ShowPicturePlaceHolders = False
      .ShowFieldCodes = False
      .ShowBookmarks = False
      .FieldShading = wdFieldShadingWhenSelected
      .ShowTabs = False
      .ShowSpaces = False
      .ShowParagraphs = False
      .ShowHyphens = False
      .ShowHiddenText = False
      .ShowAll = True
      .ShowDrawings = True
      .ShowObjectAnchors = False
      .ShowTextBoundaries = False
      .ShowHighlight = True
   End With
End With

View, Turn Off View Bookmarks:
ActiveWindow.View.ShowBookmarks = False

« W »

Window, Maximize Application Window:
Application.WindowState = wdWindowStateMaximize

« X »

« Y »

« Z »

Copyright © 2010 by the Zawawi Corporation, Glendale, CA. All Rights Reserved. Site Designed by ZCoding.