Macro CMD
Macro CMD
Text-only version
Zawawi Corp
Home
Blog
Resources
Contact Us
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