`

操作Word文档的VBA代码例子

阅读更多

抄抄书,省得到处找

==========================

 

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 »

分享到:
评论

相关推荐

    VB.NET向Word VBA传递参数,并调用Word VBA生成Word报告或PDF文档

    之前我们看到用VB.NET调用Excel VBA的例子比较多,本次是使用VB.NET向Word VBA传递参数,并调用Word VBA生成Word报告或PDF文档。 在Word VBA中,可访问数据库,获得自己想展示的数据,灵活度比较高。 运行环境:VS...

    易语言对象操作word纯源码

    用对象纯源码实现word的操作,纯绿色,无公害.关于易语言操作word读写或者向word中插入...本贴关于创建word文档等基本的就不说了,主要是对打开的word文档进行操作,实现了以下主要功能:。主要功能:。1, 表格中定位插入图

    WORD·VBA入门教程(第一课).pdf

    VBA编程多个例子,适合初学者进行系统学习,如果好评的话,后面会继续上传更多资源,希望大家多多支持,有需要资源的可以私信我

    Excel VBA 368个典型实例

    最经典的Excel VBA 实习实例,共368个excel文件,带word文件,资料齐全,物超的值 1.1 创建宏 1 例001 在Excel 2003中录制宏 1 例002 打开Excel 2007的录制宏功能 3 例003 在Excel 2007中录制宏 4 例004 使用Visual ...

    vb操作word2003的例子

    在VBA中,工具-引用,选取“MicroSoft Word 11.0 Object Library”。 方法一、New Word.Application Dim Wordapp As Word.Application Set Wordapp = NewWord.Application Wordapp.Visible = True '可见 '...

    欣闻袁版主大作《Excel VBA 常用代码实战大全》全四卷打包下载,原价26,现价只要5!!!

    大家在学习VBA的过程中,相信都有收集代码的习惯,我也是,硬盘中藏有许多VBA实例、代码,在去年《VBA精粹》的写作过程中更是在网络上收集了大量的VBA资料。...在完成全部内容后我会将Word文档上传。

    利用VB读取WORD文件的例子

    一个利用VB读取WORD文档的源程序.写得不太好,但是可以有所启发,然后了解在VB中如何通过VBA来控制WORD文档.

    VBA编程在Word中的运用

    介绍了两个例子,讲解如使用VBA编程操作word。

    VBA手册CHM版

    找到一个CHM文件的VBA手册,很好用。还有一个word使用技巧和Excel使用技巧。以及一个使用python win32读取Excel的例子

    易语言-易语言对象操作word纯

    本贴关于创建word文档等基本的就不说了,主要是对打开的word文档进行操作,实现了以下主要功能: 主要功能: 1, 表格中定位插入图片 2, 表格中定位单元格填内容 3, doc文档中按行定位并写入文本 4, doc文档中按表格...

    ACCESS+VBA编程.rar

    本书为WORD格式文档教程,全面介绍ACCESS数据库基本操作及其控件的使用,重点讲解VBA开发ACCESS,通过具体例子说明VBA语法,函数以及模块应用,并有一个VBA开发ACCESS数据库综合应用系统的实例。

    C#对Excel的读写操作

    对于Excel、word等office组件的操作,可以借鉴以前的VBA。 另外,如果不太清楚你需要的操作所对应的方法和属性,可以在office组件中开启宏录制,进行测试操作后,再编辑宏,就能在宏代码中找到自己需要的内容。

    office word 2013 编程手册

    最新的操作word,电子书,WORD vba编程的参考手册,非常详细的介绍了编程概念以及各对象、属性、事件等的使用。并提供了很多实际例子,这些例子只要复制到WORD宏中运行,马上就能看到运行的... 如果运行不现实内容...

    word2010插入目录

    本文档是使用大纲视图的形式更改标题级别,然后生成目录。首先声明这种方法有个弊端就是如果在使用大纲视图之前各个标题有编号,在大纲视图下更改标题级别时可能会使编号消失,需要重新插入编号,这只是生成目录的一...

    用对象操作word纯源码-易语言

    本贴关于创建word文档等基本的就不说了,主要是对打开的word文档进行操作,实现了以下主要功能: 主要功能: 1,表格中定位插入图片 2,表格中定位单元格 填 内容 3, doc文档中按行定位并写入文本 4,doc文档中按表格定位到...

    Word排版艺术 part 2

    本书告诉您Word的能与不能。...(4) 本书让您成为Word最高阶用户:以宏/VBA程序设计对Word进行二次开发。并附数个实用例子。 (5) 本书谈如何将Word的工作成果轻松转换为PDF格式,并保留所有目录、书签、交互参照...。

    Word排版艺术 part 1

    本书告诉您Word的能与不能。...(4) 本书让您成为Word最高阶用户:以宏/VBA程序设计对Word进行二次开发。并附数个实用例子。 (5) 本书谈如何将Word的工作成果轻松转换为PDF格式,并保留所有目录、书签、交互参照...。

    office 办公软件中利用VBA(Visual Basic for Application)宏

    .FileType = msoFileTypeWordDocuments '查找文件类型为word文档 .Execute For i = 1 To .FoundFiles.Count Documents.Open (.FoundFiles(i)) ActiveDocument.Select With Dialogs(wdDialogEditReplace) On ...

    matlab加粗代码-reportgen_matlab:利用Matlab生成报告(Word、PPT)

    matlab 加粗代码 reportgen 本文将介绍Matlab的一个实用...在第二、三行中我们新建一个文档,其中文件类型docx可以替换成html或者pdf. Document类的相关属性可以通过命令查看 (doc mlreportgen.dom.Document) append(d

Global site tag (gtag.js) - Google Analytics