Excel VBA operating Word (Beginners)

The object of this article is: There is some basis for Excel VBA, VBA for Word there is little understanding, like in Excel via VBA in Word there are difficulties.
 
First, the new Word references
We need to create a reference to the Word Application object. In VBA, Tools - References, select "MicroSoft Word 11.0 Object Library".
A method, New Word.Application
    Dim Wordapp As Word.Application
    Set Wordapp = NewWord.Application
    Wordapp.Visible = True 'visible
    'Wordapp.ScreenUpdating = False' screen refresh
    Dim WordD As Word.Document 'defined word class
    Set WordD = Wordapp.Documents.Add 'New Document
    'Set WordD = Wordapp.Documents.open (filename)' Open the document
    '……
    WordD.Close 'Close the document
    Set WordD = Nothing
    WordApp.Quit 'quit Word Object
Method two, CreateObject
    Dim WordApp As Object
    Set WordApp = CreateObject ( "Word.Application") 'New Word object
'Subsequent operations and exit the same ......
Method three, GetObject
If the file has been opened, use: SetWordD = GetObject (filename), may establish a reference to the document, if the file is not open, you need to first with one or two methods to operate.
As for the difference between the method and a second method, and asked about the Internet, masters replied:
Method One: early binding, the advantage is enter a period after the object can give quick tips, because you need to reference objects, it is compatible versions prone to problems.
Method Two: late binding, without prompting, to create an object depending on the version to run code on the target machine, good compatibility.
Tip: Sometimes the two are quite different, searchable forums dictionary object, it is recommended to use early binding when writing code that uses late binding when released.
 
Second, understanding the structure of the Word
Excel are:
Excel.Application                        ’Excel引用
Excel.Application. Workbooks' workbook
Excel.Application. Workbooks.Sheets (1) 'worksheet
The work table is a Range, region; Cells (row, col), Cell
Word has:
Word.Application
Word.Application.Documents' documents
There are characters, words, sentences, paragraphs and sections under the document. Characters to form words, words form sentences, sentences paragraphs. In addition, each document having a Sections collection comprising one or more sections, each section of the section has a header and footer HeadersFooters comprising collection.
Characters(index)
Words(index)
Sentences(index)
Paragraphs(index)
Sections(index)
The first three return Range object, modify the Range object can directly use or method of any region attributes. Two rear returns a single member of the set, instead of the Range object can not directly use the region property or method. Examples used as follows: Words (1) directly behind .Copy, and a plurality of Range between .Paragraphs (1) and .Copy.
Selection.Words(1).Copy
ActiveDocument.Paragraphs(1).Range.Copy
Characters: character, ActiveDocument.Sentences (1) .Characters.Count, the total number of characters in the first sentence.
Words: words for English is a space between two letters plus spaces for Chinese, a punctuation mark, a character, or a word (phrase in the definition of input method according to Microsoft?). (Feeling is not very reliable?)
Sentences: sentences with a period end? Feeling is not a very reliable range of feeling or character, paragraph, section, control some of them fly.
Range object represents a contiguous range in the document, the position of a character and a character start position defined termination. This range can be as small as a continuous insertion point to the entire document.
    Dim rngPa As Range
    Set rngPa = ActiveDocument. Characters (1) 'the first character
    Set rngPa = ActiveDocument.Range( _
       Start:=ActiveDocument.Paragraphs(1).Range.Start, _
       End: = ActiveDocument.Paragraphs (4) .Range.End) 'to paragraph 1 paragraph 4
    Set rngPa = ActiveDocument.Range (Start: = 0, End: = 10) 'document currently before the 10 characters
    rngPa.Select
Selected, I think of little use, because that is why it selected? Able to operate direct operation, can not, then you select it (he can say is no way to approach).
:( assignment range of objects include any object, Set is a standard statement for the object assignment)
set a=b
And assignment of variables: a = 1 is not the same
 
Third paragraph: produced by recording the macro code is modified as follows:

Third, by recording the macro code generation
with knowledge of the basic structure of the Word, to what method should be used to operate these objects, which attributes to modify? I do not know to "record a macro." We recognize that you record a macro is one great way to unknown object, macro recorder by operating translated Word Visual Basic code, and then modify the code as needed. Word and Excel are recorded is different, can not use the mouse to move the cursor or select a row only use the keyboard to move, or by arrow keys to select Shift +. The following is the keyboard of a few words: up, down, left, right, Home, End, Shift + Left select five characters, Shift + Right select five characters.
    Unit Selection.MoveUp: = wdLine, the Count: =. 1
    Selection.MoveDown Unit: = wdLine, the Count: =. 1
    Selection.MoveLeft Unit: = wdCharacter, the Count: =. 1
    Selection.MoveRight Unit: = wdCharacter, the Count: =. 1
    Selection. Unit Homekey: = wdLine
    Selection.EndKey Unit: = wdLine
    Selection.MoveLeft Unit: = wdCharacter, the Count: =. 5, Extend: = wdExtend
    Selection.MoveRight Unit: = wdCharacter, the Count: =. 5, Extend: = wdExtend
Recorded macro uses the Selection property to return the Selection object. Namely: Recorded Macro Selection always begin with, above. To use this Selection., Sometimes we have to first on a particular object .Select, selected.
Of course, Selection is a Range, Characters, Words, Sentences also Range, Paragraphs (n). Range , Sections (2). Range is Range, then we can Selection. Behind the statement grafted to the front of the Range after, do not .Select the first.
Recorded macro, and then by grafting or copied into EXCEL VBA, some running to be wrong, you should check the following items:
1, the first requirement of "reference" established yet?
2, using the VBA reminder to check the statement. VBA editing process, usually lay. After the (early binding needs?), The object of all the methods, properties will be displayed using this feature, you can check the recorded macro, can be grafted to a subject in need after the operation. Suggesting there could no you can not.
3, part of the transfer function, Word VBA there, Excel VBA there may not have encountered such a situation, it may be wrong.
Example:
WordD.Paragraphs (. 1) .Range.ParagraphFormat.FirstLineIndent CentimetersToPoints = (0.35)
Selection.ParagraphFormat.FirstLineIndent = CentimetersToPoints (0.35) is the "first line indent 2 characters," the recording operation, after grafting, run error, according to the method 2 Check: .ParagraphFormat.FirstLineIndent can be used after the Range, then that is CentimetersToPoints (0.35) there is a problem? This is obviously a function, which literally means "cm converted into points", (obviously my input when recording is "2 character", recorded ye became centimeters it?) Is that not the function in Excel VBA it ? (I do not know), will be replaced by digital = directly behind run through the last test = 20 down the equivalent of about 5 words of "first line indent 2 characters." (This 20 is 20Points? 0.35cm = 20 Points?)
(Some might say such a stupid way, what better way please let me know. Xianxie!)
 
Four, Word vba common statement 100
1, the system parameters
(01) Application.ActivePrinter 'Get the current printer
(02) Application.Height' the height of the current application document 
(03) Application.Width 'current width of the application documents 
(04 ) Application.Build 'Word Gets the version number and build number 
(05) Application.Caption' current application name 
(06) Application.DefaultSaveFormat 'returns an empty string representing the Word document 
(07) Application.DisplayRecentFiles' returns whether to show the most recently used the state of the document 
(08) Application.Documents.Count 'returns the number of currently open document 
(09) Application.FontNames.Count' returns the number of fonts currently available 
(10) Application.Left 'returns the current horizontal location of the document 
(11) Application.MacroContainer.FullName 'return to the current document name, including the path 
Application.MacroContainer.pach' return to the current document path
Application.ActiveDocument.Path 'relative path to access a file 
(12) Application.NormalTemplate.FullName' return to the standard template name and location of the document 
(13) Application.RecentFiles.Count 'Returns the number of recently opened documents 
(14) Application.System. CountryRegion 'return to the application where the area code 
(15) Application.System.FreeDiskSpace' returns to the application where disk space 
(16) Application.System.HorizontalResolution 'return horizontal resolution of the display 
(17) Application.System.VerticalResolution' returns vertical resolution of the display 
(18) Application.System.LanguageDesignation 'returns the language used by the system 
(19) Application.System.MathCoprocessorInstalled' to return the system is installed math coprocessor 
Application.System.OperatingSystem (20) 'returns the current operation name system 
(21) Application.System.ProcessorType 'returns the name of the computer processor 
(22) Application.System.Version' returns the version number of the operating system 
(23) Application.Templates.Count 'returns the number of modules used by the application 
(24) Application.UserName' returns to the application user name
(25) Application.Version 'returned to the application version

2, Documents / Document objects 
(26 ) ActiveDocument.AttachedTemplate.FullName 'return to the current document using the template name and location of the template
(27) ActiveDocument.Bookmarks.Count' returns the number of bookmarks in the current document
(28) ActiveDocument.Characters.Count 'returns the number of characters in the current document
( 29) ActiveDocument.CodeName 'returns the name of the document of the current code
(30) ActiveDocument.Comments.Count' return to the current document number of comments
(31) ActiveDocument.Endnotes.Count 'returns the number of the current document endnote
(32) ActiveDocument. Fields.Count 'returns the number of fields in the current document
(33) ActiveDocument.Footnotes.Count' footnote returns the number of documents in the current
(34) ActiveDocument.FullName 'returns the full name and location of the current document
(35) ActiveDocument.HasPassword 'whether the current document is password-protected
(36) ActiveDocument.Hyperlinks.Count' returns the number of links in the current document
(37) ActiveDocument.Indexes.Count 'returns the index number of the current document
(38) ActiveDocument. ListParagraphs.Count 'returns the current item number signed document or item
(39) ActiveDocument.ListTemplates.Count' returns the number of list template used in the current document
(40) ActiveDocument.Paragraphs.Count 'returns the number of paragraphs in the current document
(41 ) ActiveDocument.Password = XXX 'is provided to open the file using the password
(42) ActiveDocument.ReadOnly' acquires the current document is read-only attribute
(43) ActiveDocument.Saved 'whether the current document is saved
(44) ActiveDocument.Sections.Count' current number of sections in the document
(45) ActiveDocument.Sentences.Count 'number of statements in the current document
(46) ActiveDocument.Shapes.Count' current number of shapes in the document, the graphics?
(47) ActiveDocument.Styles.Count '
(48) ActiveDocument.Tables.Count 'table number of the current document
(49) ActiveDocument.TablesOfAuthorities.Count' returns the current number of documents in the table of contents
(50) ActiveDocument.TablesOfAuthoritiesCategories.Count 'returns the directory number of citations document the current category
( 51) ActiveDocument.TablesOfContents.Count 'returns the number of documents in the current directory
(52) ActiveDocument.TablesOfFigures.Count' return to the graph directory of the current document number

3, Paragraphs / Paragraph objects 
(53) Selection.Paragraphs.Count 'returns the selected paragraphs region
(54) Selection.Paragraphs.First 'returns the selected region of the first section
(55) ActiveDocument.Paragraphs (1) .LeftIndent ' return value left indent the first paragraph of this document
(56) ActiveDocument .Paragraphs (1) .LineSpacing 'returns the current document spacing the first section
(57) ActiveDocument.Paragraphs (1) .OutlineLevel ' returns or sets the first paragraph of this document outline level 
.OutlineLevel = wdOutlineLevel2 'level 2
.OutlineLevel = wdOutlineLevel3 'stage. 3
(58) ActiveDocument.Paragraphs (. 1) .RightIndent' returns documents in the first paragraph of this right indent 
(59) ActiveDocument.Paragraphs (1) .SpaceBefore ' return to the current document in the first paragraph spacing the front section 
(60) ActiveDocument.Paragraphs (1) .SpaceAfter ' returns documents in the first paragraph after the current segment a pitch 
(61) ActiveDocument.Paragraphs (1) .Range.Text ' returns the contents of the first paragraph of this document 
(62) ActiveDocument.Paragraphs (1) .Range.Style.NameLocal ' return to the first paragraph of the document apply the current style name 
(63) ActiveDocument.Paragraphs (1) .Range.Style.Description ' return to the first paragraph of the current document detailed description of the applied pattern 
(64) ActiveDocument.Paragraphs (1) .Range.Style.Font.Name ' return to the current document in the first paragraph style of a font name of the application 
(65) ActiveDocument.Paragraphs (1) .Range.Style .Font.NameFarEast 'An East Asian returns or sets the font name 
(66) ActiveDocument.Paragraphs (1) .Range.Style.Font.Size ' returns or sets the current document in the first paragraph styles applied font size 
(67) ActiveDocument.Paragraphs (1) .Range.Style.Font.Spacing ' returns or sets the character spacing
(68) Selection.Words.Count' Sentences target words selected area 
(69) Selection.Sentences.Item (1) 'selected area of the first sentence of content words object 
(71) ActiveDocument.Words (1) .Select ' select the first word in the current document 
(72) ActiveDocument.Range.Words (1) .InsertAfter " I love you! '' is inserted after the first word in the current document, "I love you" 

4, characters target 
(73) Selection.Characters.Count 'current number of characters in the selected area of the document 
(74) ActiveDocument.Paragraphs (1 ) .Range.InsertParagraphAfter 'insert a new paragraph after the current in the first paragraph of the document 

5, Sections / Section objects 
(75) ActiveDocument.Sections.First' current first document 
(76) ActiveDocument.Sections.First.PageSetup. BottomMargin 'current bottom margin of the page on the first document 
(77) ActiveDocument.Sections.First.PageSetup.LeftMargin'  The current document left from the first section of the page on
(78) ActiveDocument.Sections.First.PageSetup.RightMargin 'where the right of the current page from the first document 
(79) ActiveDocument.Sections.First.PageSetup.TopMargin' top margin of the current document page where the first
(80) ActiveDocument.Sections.First.PageSetup.PaperSize 'returns or sets the first page where the size of the document 
returns or sets the current document page containing the first (81) ActiveDocument.Sections.First.PageSetup.PageHeight' height 
(82) ActiveDocument.Sections.First.PageSetup.PageWidth 'returns or sets the first page where the width of the document 
(83) ActiveDocument.Sections.Add Range: = myRange ' add a new section in the current document 
(84) ActiveDocument.Sections.Item (2) 'document of the second current 
(85) ActiveDocument.Sections.Last.Range.InsertAfter "end of the document!' 'added the last in the current document at the end of a word" end of the document! " 

6, the Range Object 
( 86) ActiveDocument.Range (Start: = 0 , End: = 10) ' represents a Range object before the document is currently composed of 10 characters 
(87) the Set myRange = ActiveDocument.Range (the Start: = ActiveDocument.Paragraphs (2) .Range.Start, _ 
End: = ActiveDocument.Paragraphs (4) .Range.End) 'to paragraphs 2 to paragraph 4 of this document setting a Range object 
(88) ActiveDocument.Paragraphs (1) .Range.Copy ' copy of the first paragraph of this document 
(89) Selection.Copy 
Documents.Add.Content.Paste' copy the selection to the new document 
( 90) ActiveDocument.Bookmarks ( "Book1") copy Name:. = "Book2" ' copy bookmark location Book1 Book2 bookmarked 
(91) Selection.GoTo What: = wdGoToLine , Which: = wdGoToAbsolute, Count: = 4' will selected items to the first line in the document. 4 
(92) What Selection.GoTo: = wdGoToTable, Which: = wdGoToNext 'under the selection to a cell of a table 
(93) Selection.Range.AutoFormat 'apply format selection 
(94) ActiveDocument.Content.Font.Name = "Arial" ' the current document italic font 
(95) ActiveDocument.Content.Select Selection.Delete 'the contents of the current document delete other 
(96) Documents.Add' add a new document 
(97) Set myTable = ActiveDocument.Tables.Add ( Selection.Range, 2, 2 ) '2 was added a table rows and two columns in the current document selected area 

7, file read and write
(98) open "C: \ my.txt" for input As # 1' to open a file for input and allowed number is 1 
(99) the input Line # 1, the TextLine 'is opened for reading an input document and a number of 
(100) Close # 1' Close file No. 1
 
Five examples. All operation in the recording, and then grafted.
Example: using Excel VBA, Excel spreadsheet will look like (examination system derived exam), generated as a Word document
procedures Name Title Contents answer questions A Answer B Answer C answers correct answer scores whether D graphics
protocol 1 multiple-choice questions Question 1 ...... ...... ...... ...... ...... 2 ABCD         
procedure determines a title to title 2 ...... 2         
                                                                                  
protocol choice title 2 3 ...... ...... ...... ...... ...... A 2         
procedure 2 4 ...... topic title determined error 2         

procedure 1
a, choice
1, the title ...... 1 (ABCD)
a, ......
B, ......
C, ......
D, ......

Second, determine the title
1, title 2 ...... (p)
protocol 2
First, the choice
1, ...... subject. 3 (A)
A, ......
B, ......
C, ......
D, ......

Second, determine the title
1, title 4 ...... (wrong)


Sub ScWordWd ()
'the "Exam "in the title, the format of Word document
    Dim the I of As Integer, J of As Integer, ZHS of As Integer, Xh of As Integer, Dls of As String
    Dim Lr of of As String, of Bt of As String, Bt1 of As String, the Tx of As String, Tx1 of As String
    of Lj of As String Dim, WJM of As String
    Dim AA
    
    Sheets ( "exam") .Select
    ZHS = Sheets ( "exam") .UsedRange.Rows.Count
    of Bt = Cells (2,. 1) 'title
    Tx = Cells (2, 2) 'Questions
    Xh =. 1'
    Dls =. 1 '
    
    ' of As Object Dim WordApp
    'Set WordApp = CreateObject ( "Word.Application ")' New Word Object
    
    Dim WordApp of As of the Word.Application
    the Set WordApp = New of the Word.Application 'New Word object
    Wordapp.Visible = True' visible
    'Wordapp.ScreenUpdating = False' screen refresh
    
    Dim WordD As Word.Document 'defined word class
    Set WordD = Wordapp.Documents.Add' New document
    
    Wordapp.Selection.WholeStory 'Select
    Wordapp.Selection.Font.Name = "Arial"' Font
    Wordapp.Selection.Font.Size = 10 'size
    
    the For the To the I = 2 ZHS
        Bt1 = Cells (the I,. 1)
        WordD.Paragraphs (Dls) .Range.Font.Name = "Arial" 'Font
        WordD.Paragraphs (Dls) .Range.Font.Size = 10 'famous
        the If Len (Trim (Bt1))> 0 the Then
            Tx1 = Cells (the I, 2)
            Lr of Cells = (the I,. 3)
            the If Bt1 <> the Then of Bt' different titles, the title written, centering
                the If the I> the Then. 5 '
                    WordD.Paragraphs (Dls) .Range.InsertAfter (vbCrLf)' insert carriage return, a period of increasing
                    Dls = Dls +. 1
                    WordD.Paragraphs (Dls) .Range.Select
                    ' the Type Wordapp.Selection.InsertBreak: = wdPageBreak
                    'WordD.Paragraphs (Dls) .Range.InsertBreak the Type: = wdPageBreak' insert page breaks, neither of reaction?
                    Wordapp.Selection.InsertBreak Type: = wdSectionBreakNextPage 'insert a section break (next page)
                    WordD.Paragraphs (Dls) .Range.InsertAfter (vbCrLf)' Insert carriage return, a period of increasing
                    Dls Dls +. 1 =
                End the If
                of Bt = Bt1
                WordD.Paragraphs (Dls) .Range.Text = Bt & vbCrLf ' write title
                ' WordD.Paragraphs (Dls) .Range.InsertAfter (vbCrLf ) ' insert carriage return, a period of increasing
                WordD.Paragraphs (Dls) .OutlineLevel = wdOutlineLevel2' set outline level, level 2
                'WordD.Paragraphs (Dls) .Range.ParagraphFormat.FirstLineIndent = CentimetersToPoints (0)
                WordD.Paragraphs (Dls) .Range.ParagraphFormat. FirstLineIndent = 0 'to cancel the first line indent
                'WordD.Paragraphs (Dls) .Range.Font.Name = "Arial"' Font
                'WordD.Paragraphs (Dls) .Range.Font.Size = 10 ' font
                WordD.Paragraphs (Dls) .Range.ParagraphFormat.Alignment = wdAlignParagraphCenter 'center-aligned
                WordD.Paragraphs (Dls) .Range.Font.Bold = wdToggle' bold
                Dls Dls +. 1 =
                Xh. 1 =
            End the If
            the If Tx1 <> the Then the Tx 'different kinds of questions, write questions
                If Tx1 = "choice "the Then
                    WordD.Paragraphs (Dls) .Range.Text =" First, the choice " 'written questions
                Else
                WordD.Paragraphs (Dls) .Range.InsertAfter (vbCrLf) ' Insert carriage return, a period of increasing
                Dls = Dls +. 1
                    WordD.Paragraphs (Dls) .Range.Text = "Second, determine the title"' written questions
                End the If
                the Tx Tx1 =
                WordD.Paragraphs (Dls) .Range.ParagraphFormat.Alignment = wdAlignParagraphJustify 'left-aligned
                ' WordD.Paragraphs (Dls) .Range.ParagraphFormat.FirstLineIndent = CentimetersToPoints (0.35) ' first line indent 2 characters, can not be used when , CentimetersToPoints not recognized Excel?
                WordD.Paragraphs (Dls) .Range.ParagraphFormat.FirstLineIndent = 20 'first line indent, equivalent to approximately 20 5 2 character word
                WordD.Paragraphs (Dls) .Range.InsertAfter (vbCrLf) '
                WordD.Paragraphs(Dls).Range.Font.Bold = wdToggle           '加粗
                Dls = Dls + 1
                Xh = 1
            End If
            If Tx = "选择题" Then
                WordD.Paragraphs(Dls).Range.Text = Xh & "、" & Lr & "  (" & Cells(I, 8) & ")" & vbCrLf      '写题目及标准答案
                Dls = Dls + 1
                WordD.Paragraphs(Dls).Range.Text = "A、" & Cells(I, 4) & vbCrLf        '选项A
                Dls = Dls + 1
                WordD.Paragraphs(Dls).Range.Text = "B、" & Cells(I, 5) & vbCrLf        '选项B
                Dls = Dls + 1
                WordD.Paragraphs(Dls).Range.Text = "C、" & Cells(I, 6) & vbCrLf        '选项C
                Dls = Dls + 1
                If Len(Trim(Cells(I, 7))) > 0 Then
                    WordD.Paragraphs(Dls).Range.Text = "D、" & Cells(I, 7) & vbCrLf        '选项D
                    Dls = Dls + 1
                End If
                Xh = Xh + 1
            Else
                WordD.Paragraphs(Dls).Range.Text = Xh & "、" & Lr & "  (" & Cells(I, 8) & ")" & vbCrLf      '写题目及标准答案
                Dls = Dls + 1
                Xh = Xh + 1
            End If
        End If
    Next I
    Wordapp.WindowState = wdWindowStateMinimize      '最小化窗口
    'Wordapp.ScreenUpdating = True 'screen refresh
    'WordD.Close                             '
    'Set WordD = Nothing
    'Set Wordapp = Nothing
    'Wordapp.Quit                        '退出Word对象
    
    ThisWorkbook.Activate
End Sub
(Finish)

Guess you like

Origin www.cnblogs.com/medik/p/10989722.html