word-vba application

The object of this article is: There is a certain Excel VBA foundation, there is no understanding of Word VBA, people who want to operate Word through VBA in Excel are still difficult.

1. New Word Reference You
need to first create a reference to the Word Application object. In VBA, Tools-Reference, select "MicroSoft Word 11.0 Object Library".
Method 1: 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' Define the word class
Set WordD = Wordapp. Documents.Add 'New Document
' Set WordD = Wordapp.Documents.open (filename) 'Open Document
' ...
WordD.Close 'Close Document
Set WordD = Nothing
WordApp.Quit' Exit Word Object
Method Two, CreateObject
Dim WordApp As Object
Set WordApp = CreateObject ("Word.Application") The
follow-up operation and exit of 'New Word Object ' are the same ...
Method Three, GetObject
When the file is already open, use: SetWordD = GetObject (filename) to establish a reference to the document. If the file is not open, you need to use method one or two first.
As for the difference between method one and method two, I asked on the Internet. The answer of the masters is:
Method one: early binding, the advantage is that entering a period after the object can give a quick reminder, because you need to refer to the object first, so it is easy to appear Version compatibility issues.
Method 2: Late binding, no prompt, create an object according to the version of the object on the machine running the code, and the compatibility is good.
Tip: Sometimes there is a big difference between the two. You can search the dictionary object in the forum. It is recommended to use early binding when writing code and late binding when publishing.

Second, understand the structure of Word
Excel:
Excel.Application 'Excel references
Excel.Application. Workbooks' workbook
Excel.Application. Workbooks.Sheets (1)' Worksheet worksheet
is Range, area; Cells (row, col) , The cell
Word has:
Word.Application
Word.Application.Documents' documents
under the document there are characters, words, sentences, paragraphs and sections. Characters form words, words form sentences, and sentences form paragraphs. In addition, each document has a Sections collection that contains one or more sections, and each section has a HeadersFooters collection that contains the section header and footer.
Characters (index)
Words (index)
Sentences (index)
Paragraphs (index)
Sections (index) The
first three return Range objects, you can directly use any area properties or methods to modify the Range object. The last two return a single member of the collection, not a Range object, and you cannot directly use a local property or method. The following usage example: Words (1) directly after .Copy, and there is a Range between .Paragraphs (1) and .Copy.
Selection.Words (1) .Copy
ActiveDocument.Paragraphs (1) .Range.Copy
Characters: characters, ActiveDocument.Sentences (1) .Characters.Count, the total number of characters in the first sentence.
Words: Words, for English, are letters between two spaces plus spaces, for Chinese, a punctuation mark, a Chinese character, or a word (as defined by the phrase in Microsoft's input method?). (It doesn't feel very reliable?)
Sentences: Sentences, ending with a period? I do n’t think it ’s a very reliable range. I feel it ’s still characters, paragraphs, and sections. It ’s more reliable to control.
The Range object represents a continuous range in the document, defined by a starting character position and a ending character position. This continuous range can be as small as an insertion point and as large as the entire document.
Dim rngPa As Range
Set rngPa = ActiveDocument. Characters (1) 'First character
Set rngPa = ActiveDocument.Range (_
Start: = ActiveDocument.Paragraphs (1) .Range.Start, _
End: = ActiveDocument.Paragraphs (4) .Range.End) '
Set rngPa = ActiveDocument.Range (Start: = 0, End: = 10) from the beginning of the first paragraph to the end of the fourth paragraph .' The first 10 characters of the current document are selected by
rngPa.Select
, I think it is not very useful , The reason is why is it selected? If you can, you can operate it directly. If you ca n’t, just choose it (he can say that there is no way).
Assignment of range objects: (including arbitrary objects, Set is the standard statement for assigning objects)
set a = b
And variable assignment: a = 1 is not the same

The third paragraph: Generate code by recording macros, amended as follows:

Third, generate code by recording macros
With an understanding of the basic structure of Word, what methods should be used to manipulate these objects and what attributes should be modified? "Record a macro" if you don't know. Recording macros is one of the good ways for us to recognize unknown objects. The macro recorder translates the operations into Word's Visual Basic code, and then modifies the code as needed. The difference between recording in Word and Excel is that you can't use the mouse to move the cursor or select a row, you can only use the keyboard to move, or use Shift + arrow keys to select. The following sentences are on the keyboard: up, down, left, right, Home, End, Shift + left select 5 characters, Shift + right select 5 characters.
Selection.MoveUp Unit: = wdLine, Count: = 1
Selection.MoveDown Unit: = wdLine, Count: = 1
Selection.MoveLeft Unit: = wdCharacter, Count: = 1
Selection.MoveRight Unit: = wdCharacter, 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 macros use The Selection property returns a Selection object. That is: the recorded macro always starts with Selection., As above. To use this Selection, sometimes we have to select the specific object.
Of course, Selection is a Range, Characters, Words, and Sentences are also Ranges, Paragraphs (n). Range, Sections (2). Range is also Range, then we can marry the statements after Selection. First, select.
After the recorded macro is grafted or copied to EXCEL VBA, some operations will be wrong. At this time, the following items should be checked:
1. Has the "reference" required in the first item been established?
2. Use the VBA reminder function to check statements. During the VBA editing process, usually after typing. (Needs early binding?), All methods and properties of the object will be displayed. Using this feature, you can check whether the recorded macro can be grafted to the object that needs to be operated. You can do it if you have it, but you can't if you don't.
3. Some conversion functions are available in Word VBA and may not be available in Excel VBA. In such cases, errors may occur.
Example:
WordD.Paragraphs (1) .Range.ParagraphFormat.FirstLineIndent = CentimetersToPoints (0.35)
Selection.ParagraphFormat.FirstLineIndent = CentimetersToPoints (0.35) is recorded by "first line indent 2 characters" operation, after grafting, the operation error, check according to method 2: .ParagraphFormat.FirstLineIndent can be used after Range, then it is CentimetersToPoints (0.35) there is a problem? This is obviously a function, which literally means "centimeters converted into points" (I explicitly entered "2 characters" when recording, and what was recorded as centimeters?) Is it not in Excel VBA ? (I do n’t know), change the number directly after = to run through, and finally try it out = 20 is equivalent to the "first line indented by 2 characters" of size 5. (This 20 is 20 Points? 0.35cm = 20 Points?)
(Some people may say that this method is too stupid, please let me know if there is a good way . Thanks in advance !)

Fourth, Word vba common sentences 100 sentences
1, system parameters
(01) Application.ActivePrinter 'Get the current printer
(02) Application.Height' Current application document height
(03) Application.Width 'Current application document width
(04 ) Application.Build 'Get Word version number and compilation number
(05) Application.Caption' Current application name
(06) Application.DefaultSaveFormat 'Returns an empty string, which means that the Word document
(07) Application.DisplayRecentFiles' Return whether to display the most recently used The status of the document
(08) Application.Documents.Count 'Returns the number of currently open documents
(09) Application.FontNames.Count' Returns the number of currently available fonts
(10) Application.Left 'Returns the horizontal position of the current document
(11) Application.MacroContainer.FullName 'Return the current document name, including the path
Application.MacroContainer.pach' Return the current document path
Application.ActiveDocument.Path 'Get the relative path of the file
(12) Application.NormalTemplate.FullName' Return the document standard template name and location
(13) Application.RecentFiles.Count 'Returns the number of recently opened documents
(14) Application.System.CountryRegion' Returns the region code of the application
(15) Application.System.FreeDiskSpace 'Returns the available disk space of the application
(16) Application.System.HorizontalResolution 'Return the horizontal resolution of the display
(17) Application.System.VerticalResolution' Return the vertical resolution of the display
(18) Application.System.LanguageDesignation 'Return the language used by the system
(19) Application.System.MathCoprocessorInstalled 'Return whether the system has installed a math coprocessor
(20) Application.System.OperatingSystem' Return the current operating system name
(21) Application.System.ProcessorType 'Return the computer processor name
(22) Application.System.Version' Return to the operating system The version number
(23) Application.Templates.Count 'Returns the number of templates used by the application
(24) Application.UserName' Returns the application user name
(25) Application.Version 'Returns the version number of the application

2. Documents / Document object
(26) ActiveDocument.AttachedTemplate.FullName 'Return the template name and location of the template used in the current document
(27) ActiveDocument.Bookmarks.Count' Return the number of bookmarks in the current document
(28) ActiveDocument.Characters.Count 'Return the number of characters in the current document
(29) ActiveDocument.CodeName' Return the code name of the current document
(30) ActiveDocument.Comments.Count 'Return the number of comments in the current document
(31) ActiveDocument.Endnotes.Count' Return the current document Endnotes
(32) ActiveDocument.Fields.Count 'Return the number of fields in the current document
(33) ActiveDocument.Footnotes.Count' Return the number of footnotes in the current document
(34) ActiveDocument.FullName 'Return the full name and location of the current document Position
(35) ActiveDocument.HasPassword 'Whether the current document is password protected
(36) ActiveDocument.Hyperlinks.Count' Return the number of links in the current document
(37) ActiveDocument.Indexes.Count 'Return the number of indexes in the current document
(38) ActiveDocument .ListParagraphs.Count 'Returns the number of items or bullets in the current document
(39) ActiveDocument.ListTemplates.Count 'Returns the number of list templates used in the current document
(40) ActiveDocument.Paragraphs.Count' Returns the number of paragraphs in the current document
(41) ActiveDocument.Password = XXX 'Set the password used to open the file
( 42) ActiveDocument.ReadOnly 'Get whether the current document is read-only
(43) ActiveDocument.Saved' Whether the current document is saved
(44) ActiveDocument.Sections.Count 'Number of sections in the current document
(45) ActiveDocument.Sentences.Count' The number of statements in the current document
(46) ActiveDocument.Shapes.Count 'Number of shapes in the current document, graphics?
(47) ActiveDocument.Styles.Count 'Number of styles in the current document
(48) ActiveDocument.Tables.Count' Number of tables in the current document
(49) ActiveDocument.TablesOfAuthorities.Count 'Returns the number of citation directories in the current document
(50) ActiveDocument.TablesOfAuthoritiesCategories.Count 'Return the number of citation categories in the current document
(51) ActiveDocument.TablesOfContents.Count' Return the number of directories in the current document
(52) ActiveDocument.TablesOfFigures.Count 'Returns the number of chart directories in the current document

3. Paragraphs / Paragraph object
(53) Selection.Paragraphs.Count 'Returns the number of paragraphs in the selected area
(54) Selection.Paragraphs.First' Returns the first paragraph in the selected area
(55) ActiveDocument.Paragraphs (1). LeftIndent 'Return the left indent value of the first paragraph in the current document
(56) ActiveDocument.Paragraphs (1) .LineSpacing' Return the line spacing of the first paragraph in the current document
(57) ActiveDocument.Paragraphs (1) .OutlineLevel 'Return or set Outline level of the first paragraph in the current document.
OutlineLevel = wdOutlineLevel2 'Level
2. OutlineLevel = wdOutlineLevel3' Level 3
(58) ActiveDocument.Paragraphs (1). RightIndent 'Return the right indent of the first paragraph in the current document
(59) ActiveDocument.Paragraphs (1) .SpaceBefore 'Returns the space before the first paragraph in the current document
(60) ActiveDocument.Paragraphs (1) .SpaceAfter' Returns the space after the first paragraph in the current document
(61) ActiveDocument.Paragraphs ( 1) .Range.Text 'Return the content of the first paragraph in the current document
(62) ActiveDocument.Paragraphs (1) .Range.Style.NameLocal 'Return the style name applied in the first paragraph of the current document
(63) ActiveDocument.Paragraphs (1) .Range.Style.Description' Return the first paragraph in the current document Detailed description of the applied style
(64) ActiveDocument.Paragraphs (1) .Range.Style.Font.Name 'Returns the font name of the style applied in the first paragraph of the current document
(65) ActiveDocument.Paragraphs (1) .Range.Style .Font.NameFarEast 'Return or set a East Asian font name
(66) ActiveDocument.Paragraphs (1) .Range.Style.Font.Size' Return or set the font size of the style applied in the first paragraph of the current document
(67) ActiveDocument .Paragraphs (1) .Range.Style.Font.Spacing 'Return or set the character spacing
(68) Selection.Words.Count' Sentences object of the selected area
(69) Selection.Sentences.Item (1) 'Selected area The content of the first sentence in the Words object
(71) ActiveDocument.Words (1) .Select 'Select the first word in the current document
(72) ActiveDocument.Range.Words (1) .InsertAfter "I love you!" Insert "I love you" after the first word in the current document

4. Characters object
(73) Selection.Characters.Count 'Number of characters in the selected area of ​​the current document
(74) ActiveDocument.Paragraphs (1) .Range.InsertParagraphAfter' inserts a new paragraph after the first paragraph of the current document

5. Sections / Section objects
(75) ActiveDocument.Sections.First 'First section of the current document
(76) ActiveDocument.Sections.First.PageSetup.BottomMargin' Bottom margin of the page where the first section of the current document is located
(77) ActiveDocument. Sections.First.PageSetup.LeftMargin 'Left margin of the page where the first section of the current document is located
(78) ActiveDocument.Sections.First.PageSetup.RightMargin' Right margin of the page where the first section of the current document is located
(79) ActiveDocument.Sections.First. PageSetup.TopMargin 'The top margin of the page where the first section of the current document is located
(80) ActiveDocument.Sections.First.PageSetup.PaperSize' Returns or sets the size of the page where the first section of the current document is located
(81) ActiveDocument.Sections.First.PageSetup .PageHeight 'Returns or sets the height of the page where the first section of the current document is located
(82) ActiveDocument.Sections.First.PageSetup.PageWidth' Returns or sets the width of the page where the first section of the current document is located
(83) ActiveDocument.Sections.Add Range: = myRange 'Add a new section in the current document
(84) ActiveDocument.Sections.Item (2)' The second section in the current document
(85) ActiveDocument.Sections.Last.Range.InsertAfter "End of document!" 'Add the text "End of document!" At the end of the last section in the current document

6. Range object
(86) ActiveDocument.Range (Start: = 0, End: = 10) 'Represents a Range object composed of the first 10 characters of the current document
(87) Set myRange = ActiveDocument.Range (Start: = ActiveDocument. Paragraphs (2) .Range.Start, _
End: = ActiveDocument.Paragraphs (4) .Range.End) 'Set paragraphs 2 to 4 of the current document as a Range object
(88) ActiveDocument.Paragraphs (1). Range.Copy 'Copy the first paragraph in the current document
(89) Selection.Copy
Documents.Add.Content.Paste' Copy the selected content to a new document
(90) ActiveDocument.Bookmarks (“Book1”). Copy Name: = "Book2" 'Copy Book2 bookmark to Book1 bookmark marker location
(91) Selection.GoTo What: = wdGoToLine, Which: = wdGoToAbsolute, Count: = 4' Move the selection to line 4 in the document
(92) Selection .GoTo What: = wdGoToTable, Which: = wdGoToNext 'Move the selection to the first cell of the next table
(93) Selection.Range.AutoFormat' Apply the format to the selection
(94) ActiveDocument.Content.Font.Name = "Arial" 'Set the font of the current document to italics
(95) ActiveDocument.Content.Select Selection.Delete' Delete the contents of the current document to other
(96) Documents.Add ' Add a new document
(97) Set myTable = ActiveDocument.Tables.Add (Selection.Range, 2, 2) 'Add a table with 2 rows and 2 columns in the selected area of ​​the current document

7. File reading and writing
(98) Open “C: \ my.txt” For Input As # 1 'Open a file for input and make it numbered 1
(99) Line Input # 1, TextLine' Reading is opened File number 1 for input
(100) Close # 1 'Close file number 1

5. Examples. The operations in the example are all recorded and then grafted.
Example: Using Excel VBA, the following Excel table (the question bank exported in the examination system) will be generated as the following Word document.
Procedure name Question type question content answer A answer B answer C answer D correct answer score is there a graphical
procedure 1 multiple choice question 1 ……………………………… ABCD 2  
Procedure 1 Judgment Question 2 …… Pair 2  
                   
Procedure 2 Multiple Choice Question 3 …………………………………… A 2  
Procedure 2 Judgment Question 4 4 Wrong 2

Procedure 1
1. Multiple choice question
1, question 1 (ABCD)
A, ...
B, ...
C, ...
D, ...

2. Judgment Question
1, Question 2 ... (Yes)
Procedure 2
1. Multiple Choice
Question 1, Question 3 ... (A)
A, ...
B, ...
C, ...
D, ...

2. Judgment question
1, question 4 ... (wrong)

Sub ScWordWd ()
'Generate the Word document in the format of the "Question Bank "
Dim I As Integer, J As Integer, Zhs As Integer, Xh As Integer, Dls As String
Dim Lr As String, Bt As String, Bt1 As String , Tx As String, Tx1 As String
Dim Lj As String, Wjm As String
Dim AA

Sheets("题库").Select
Zhs = Sheets("题库").UsedRange.Rows.Count
Bt = Cells(2, 1)         '标题
Tx = Cells(2, 2)         '题型
Xh = 1                   '
Dls = 1                 '

'Dim WordApp As Object
'Set WordApp = CreateObject("Word.Application")     '新建Word对象

Dim Wordapp As Word.Application
Set Wordapp = New Word.Application      '新建Word对象
Wordapp.Visible = True                    '可见
'Wordapp.ScreenUpdating = False             '屏幕刷新

Dim WordD As Word.Document      '定义word类
Set WordD = Wordapp.Documents.Add                  '新建文档

Wordapp.Selection.WholeStory                   '全选
Wordapp.Selection.Font.Name = "宋体"           '字体
Wordapp.Selection.Font.Size = 10               '字号

For I = 2 To Zhs
    Bt1 = Cells(I, 1)
    WordD.Paragraphs(Dls).Range.Font.Name = "宋体"             '字体
    WordD.Paragraphs(Dls).Range.Font.Size = 10                 '字号
    If Len(Trim(Bt1)) > 0 Then
        Tx1 = Cells(I, 2)
        Lr = Cells(I, 3)
        If Bt1 <> Bt Then         '标题不同,写标题,居中
            If I > 5 Then       '
                WordD.Paragraphs(Dls).Range.InsertAfter (vbCrLf)   '插入回车符,增加一段
                Dls = Dls + 1
                WordD.Paragraphs(Dls).Range.Select
                'Wordapp.Selection.InsertBreak Type:=wdPageBreak
                'WordD.Paragraphs(Dls).Range.InsertBreak Type:=wdPageBreak           '插入分页符,两个都没反应?
                Wordapp.Selection.InsertBreak Type:=wdSectionBreakNextPage      '插入分节符(下一页)
                WordD.Paragraphs(Dls).Range.InsertAfter (vbCrLf)              '插入回车符,增加一段
                Dls = Dls + 1
            End If
            Bt = Bt1
            WordD.Paragraphs(Dls).Range.Text = Bt & vbCrLf            '写标题
            'WordD.Paragraphs(Dls).Range.InsertAfter (vbCrLf)        '插入回车符,增加一段
            WordD.Paragraphs(Dls).OutlineLevel = wdOutlineLevel2      '设置大纲级别,2级
            'WordD.Paragraphs(Dls).Range.ParagraphFormat.FirstLineIndent = CentimetersToPoints(0)
            WordD.Paragraphs(Dls).Range.ParagraphFormat.FirstLineIndent = 0       '取消首行缩进
            'WordD.Paragraphs(Dls).Range.Font.Name = "宋体"             '字体
            'WordD.Paragraphs(Dls).Range.Font.Size = 10                 '字号
            WordD.Paragraphs(Dls).Range.ParagraphFormat.Alignment = wdAlignParagraphCenter          '居中排列
            WordD.Paragraphs(Dls).Range.Font.Bold = wdToggle           '加粗
            Dls = Dls + 1
            Xh = 1
        End If
        If Tx1 <> Tx Then           '题型不同,写题型
            If Tx1 = "选择题" Then
                WordD.Paragraphs(Dls).Range.Text = "一、选择题"                      '写题型
            Else
            WordD.Paragraphs(Dls).Range.InsertAfter (vbCrLf)           '插入回车符,增加一段
            Dls = Dls + 1
                WordD.Paragraphs(Dls).Range.Text = "二、判断题"                      '写题型
            End If
            Tx = Tx1
            WordD.Paragraphs(Dls).Range.ParagraphFormat.Alignment = wdAlignParagraphJustify     '左对齐
            'WordD.Paragraphs(Dls).Range.ParagraphFormat.FirstLineIndent = CentimetersToPoints(0.35)       '首行缩进2字符,时能用时不能用,CentimetersToPoints不能被Excel识别?
            WordD.Paragraphs(Dls).Range.ParagraphFormat.FirstLineIndent = 20         '首行缩进,20大约相当于5号字的2字符
            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             '屏幕刷新
'WordD.Close                             '
'Set WordD = Nothing
'Set Wordapp = Nothing
'Wordapp.Quit                        '退出Word对象

ThisWorkbook.Activate

End Sub
(End)
Category: VBA
Reprinted at: https://www.cnblogs.com/ziheIT/p/8835158.html

Published 0 original articles · liked 0 · visits 0

Guess you like

Origin blog.csdn.net/mxj16888/article/details/105563642