`

操作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 »

分享到:
评论

相关推荐

    Word_vba例子源代码.pdf

    恶意宏,即宏病毒,能够破坏文档、感染其他文件或执行未经授权的操作。然而,Word提供了宏安全设置,允许用户选择性地启用或禁用宏,保护系统免受潜在威胁。 用户应该采取以下措施来确保宏的安全使用: - **了解宏...

    word中用VBA操作表格的例子

    在Word中,VBA(Visual Basic for Applications)是一种强大的编程工具,可以用来自动化文档处理,包括操作表格。本文将探讨如何使用VBA在Word中实现表格单元格底纹的自动填充功能。 首先,理解VBA的基本语法是至关...

    word VBA邮件合并及批量生成单个文档

    在这个例子中,我们将使用 Word VBA 实现批量生成申请表,并将其分割成独立的文档,每个文档的名字命名原则为申请人的名字加上所在市县名称。 邮件合并 邮件合并是 Word 中的一种功能,可以将数据源中的数据批量...

    vs2010 操作WORD VBA MFC 批注 WORD

    在本主题中,我们将深入探讨如何利用VS2010来操作Microsoft Word,特别是涉及到VBA(Visual Basic for Applications)和MFC(Microsoft Foundation Classes)在处理Word文档批注方面的应用。 首先,VBA是一种内置在...

    word-vba-详解

    总的来说,Word VBA提供了强大的工具来控制和定制Word文档。理解Document对象、其相关的集合以及如何有效地引用和操作它们是成功编写Word VBA宏的关键。同时,Range对象的灵活运用让精细的内容编辑成为可能。开发者...

    Word VBA高效排版范例应用(实例文件)

    7. **文件操作**:使用VBA可以读取、写入和创建新的Word文档,实现数据的导入导出,或者将多个文档合并为一个。 8. **邮件合并**:VBA可以进一步扩展Word的邮件合并功能,自动处理大量信函、标签或报告的生成,特别...

    VBA代码大全

    4. **查阅文档**:利用在线资源和MSDN图书馆,查阅VBA的官方文档,获取详细信息和更多例子。 5. **交流和分享**:参与VBA社区讨论,与其他开发者交流经验,提升技能。 通过以上方法,你可以逐步掌握并精通Excel ...

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

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

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

    VBA特别适用于Word文档处理,它提供的编程接口可以让我们通过编写宏来操作Word中的各种对象。 VBA的学习曲线可能比较陡峭,但对于希望提高Office应用程序自动化水平的人来说,掌握VBA是极具价值的技能。初学者可以...

    VBA实例601例子

    这通常通过`Shell`函数实现,可以用来运行操作系统命令或者执行其他程序,如打开Word文档或Excel文件,这在多应用集成的工作流程中非常有用。 2. **文档系统操作**:10 文档系统操作涵盖了文件和文件夹的管理。VBA...

    VBA word 手册

    本手册聚焦于利用VBA进行Word文档的编程,为开发者提供详尽的指导。 一、VBA基础 在VBA中,我们首先需要了解基本的编程概念,如变量、常量、数据类型(如String、Integer、Double等)、运算符和控制结构(如If......

    vba处理word图像

    通过上述代码,我们可以看到VBA的强大之处在于其能够高效地自动化重复性任务,尤其在处理大量Word文档中的图片时,能够极大地提高工作效率。掌握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 ...

    Excel-VBA宏编程实例源代码-打开指定的Word文档.zip

    打开指定的Word文档.zip"的压缩包就是一个典型的例子,它包含了一个名为"打开指定的Word文档.xlsm"的文件,该文件中可能包含了用于在Excel环境中通过VBA(Visual Basic for Applications)来打开并操作Word文档的宏...

    能够修改Word命令的VBA代码.docx

    总的来说,通过VBA,我们可以实现对Word命令的深度定制,不仅可以禁用或替换内置功能,还能添加额外的逻辑,如跟踪文档操作或执行特定任务。这极大地扩展了Word的功能,使其更适合各种专业或个性化的文档处理需求。

    易语言对象操作word纯源码

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

    vba操作excel及word的案例,rpa可用

    例如,RPA机器人可以读取Excel表格中的数据,然后根据这些数据生成Word报告,或者在Word文档中进行搜索和替换操作。这在业务流程自动化中非常实用,例如,处理客户订单、生成报表、更新数据库等。 这个压缩包中的...

    word vba高效排版范例应用1(完整版哦!)1_194

    )1_194”资源,显然是一个包含了多个VBA代码示例的集合,旨在帮助用户提升Word文档的编辑效率。在PDF文件“Word.VBA高效排版范例应用(完整版哦!)1.pdf”中,可能会涵盖以下几方面的内容: 1. **自动化格式设置**...

    owc+vba经典例子推荐

    OWC(Office Web Components)是微软提供的一种技术,允许开发者在Web页面中嵌入和操作Microsoft Office组件,如Excel、Word和Access等。VBA(Visual Basic for Applications)则是Microsoft Office套件中内置的一种...

    VBA 的一百句经典例子

    通过这些VBA的实例,我们可以看出VBA提供了丰富的接口来操作Word文档,从基本的文档属性(如大小、字符数)到更复杂的元素(如书签、注释、域和模板)。理解并熟练使用这些属性和方法,可以帮助你编写出强大的宏,...

Global site tag (gtag.js) - Google Analytics