Как в word записать строку vba

Цитата
Сообщение от Surrogate
Посмотреть сообщение

поиск кода был проделан с помощью замечательного инструмента макрорекордера !

Жаль, что результат не такой замечательны

Visual Basic
1
Selection.HomeKey Unit:=wdStory

Перемещает не в начало таблицы, а в начало документа. Они могут совпадать, но не всегда.

Visual Basic
1
Selection.MoveDown Unit:=wdLine, Count:=X

Спускается по строкам документа, а не обязательно таблицы.

Вставить строки в таблицу можно так:

Visual Basic
1
2
3
Dim tbl As Table : Set tbl = ActiveDocument.Tables(1) 'Первая таблица в документе
tbl.Rows.Add 'Добавляет новую строку в конец таблицы
tbl.Rows.Add n 'Добавляет новую строку перед указанной

Редактирование документов Word из кода VBA Excel. Добавление и форматирование текста. Объект Word.Range, свойство Text, методы InsertAfter и InsertBefore.

Работа с Word из кода VBA Excel
Часть 3. Редактирование документов Word
[Часть 1] [Часть 2] [Часть 3] [Часть 4] [Часть 5] [Часть 6]

Добавление текста в новый документ

Основные объекты, использующиеся в VBA Word для определения места вставки, добавления и форматирования текста – это Selection (выделение), Range (диапазон) и Bookmark (закладка).

Selection и Range позволяют заполнять текстом новые документы или редактировать существующие. Закладки можно использовать для вставки изменяемых реквизитов в шаблоны различных документов: договоры, акты, справки.

Объект Range имеет преимущество перед объектом Selection, так как он может быть создан только программно и не зависит от действий пользователя. Если для вставки и форматирования текста будет использоваться объект Selection, а пользователь во время работы программы просто поставит курсор в другое место документа, результат будет непредсказуем.

Word.Range кардинально отличается от объекта Range в Excel. В приложении Word он представляет из себя набор из одного или множества символов. А также он может вообще не содержать ни одного символа, а быть указателем ввода текста (виртуальным курсором).

Объект Range возвращается свойством Range других объектов приложения Word: Document, Selection, Bookmark, Paragraph, Cell (объект Table).

Вставка текста без форматирования

Если текст вставляется без форматирования, достаточно одной строки кода (myDocument – это переменная):

  • Вставка текста с заменой имеющегося: myDocument.Range.Text = "Вставляемый текст"
  • Добавление текста после имеющегося: myDocument.Range.InsertAfter "Добавляемый текст"
  • Добавление текста перед имеющимся: myDocument.Range.InsertBefore "Добавляемый текст"

Методами InsertAfter и InsertBefore можно вставить текст и на пустую страницу, также, как с помощью свойства Text. Перейти на новый абзац и начать предложение с красной строки можно с помощью ключевых слов vbCr (vbNewLine, vbCrLf) и vbTab.

Вставка текста с форматированием

Для форматирования отдельных участков текста необходимо указать диапазон символов, входящих в этот участок. Здесь нам также поможет объект Range, которому можно задать любой набор символов, содержащихся в документе Word.

Синтаксис присвоения диапазона символов объекту Range:

myDocument.Range(Start:=n, End:=m)

‘или без ключевых слов Start и End

myDocument.Range(n, m)

  • myDocument – переменная;
  • n – номер точки перед начальным символом;
  • m – номер точки после конечного символа.

Счет точек вставки начинается с нуля. Знаки переноса строки, возврата каретки и табуляции учитываются как отдельные символы. 0 – это для объекта Word.Range виртуальная точка вставки на пустом документе, 1 – точка между первым и вторым символом, 2 – точка между вторым и третьим символом и т.д.

На пустом документе объекту Range можно присвоить только виртуальную точку вставки:
myDocument.Range(Start:=0, End:=0)

Первый символ в документе с текстом:
myDocument.Range(Start:=0, End:=1)

Диапазон с 11 по 20 символ:
myDocument.Range(Start:=10, End:=20)

Реальная точка вставки (курсор) принадлежит объекту Selection, который создается вручную или программно с помощью метода Select.

Вставка курсора в начало документа:
myDocument.Range(Start:=0, End:=0).Select

Эта строка вставит курсор между пятым и шестым символами:
myDocument.Range(Start:=5, End:=5).Select

Вставка курсора в конец документа:
myDocument.Range(.Range.Characters.Count - 1, .Range.Characters.Count - 1).Select

Ссылку на объект Range можно присвоить переменной, но при форматировании ее придется каждый раз переопределять и код получится длиннее. Пример присвоения ссылки объектной переменной:

Dim myRange As Word.Range

Set myRange = myDocument.Range(Start:=0, End:=20)

Для Range(Start:=0, End:=20) в документе должно быть как минимум 20 символов.

Однострочные примеры редактирования и форматирования текста

Вставка дополнительного текста внутри имеющегося после заданной точки:
myDocument.Range(Start:=10, End:=10).InsertAfter "Вставляемый текст"

Новый абзац с красной строки (предыдущая строка должна заканчиваться символом возврата каретки или переноса строки):
myDocument.Range.InsertAfter vbTab & "Красная строка"

Присвоение шрифту заданного диапазона зеленого цвета:
myDocument.Range(Start:=10, End:=65).Font.ColorIndex = wdGreen

Меняем обычное начертание на курсив:
myDocument.Range(Start:=10, End:=65).Font.Italic = True

Указываем размер шрифта:
myDocument.Range(Start:=10, End:=65).Font.Size = 22

Применение стандартных стилей:
myDocument.Range(Start:=0, End:=16).Style = "Заголовок 1"

Если вас заинтересуют другие команды форматирования текста, запишите их макрорекордером в VBA Word и примените к объекту Range.

Пример 1
Добавление текста в новый документ без форматирования:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

Sub Primer1()

On Error GoTo Instr

Dim myWord As New Word.Application, _

myDocument As Word.Document

Set myDocument = myWord.Documents.Add

myWord.Visible = True

With myDocument

.Range.Text = «Заголовок по центру» & vbCr

.Range(Start:=0, End:=19).ParagraphFormat.Alignment _

  = wdAlignParagraphCenter

.Range.InsertAfter _

  vbTab & «Первый абзац с красной строки» & vbCr & _

  «Второй абзац не с красной строки» & vbCr & _

  vbTab & «Третий абзац с красной строки»

End With

Set myDocument = Nothing

Set myWord = Nothing

Exit Sub

Instr:

If Err.Description <> «» Then

  MsgBox «Произошла ошибка: « & Err.Description

End If

If Not myWord Is Nothing Then

  myWord.Quit

  Set myDocument = Nothing

  Set myWord = Nothing

End If

End Sub

Пример 2
Добавление текста в новый документ с форматированием:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

Sub Primer2()

On Error GoTo Instr

Dim myWord As New Word.Application, _

myDocument As Word.Document

Set myDocument = myWord.Documents.Add

myWord.Visible = True

With myDocument

.Range.Text = «Заголовок по центру» & vbCr

.Range(Start:=0, End:=19).Style = «Заголовок»

.Range(Start:=0, End:=19).ParagraphFormat.Alignment _

  = wdAlignParagraphCenter

.Range.InsertAfter «Заголовок 1 не по центру» & vbCr

.Range(Start:=20, End:=44).Style = «Заголовок 1»

.Range.InsertAfter vbTab & «Шрифт по умолчанию « _

  & «с красной строки» & vbCr

.Range.InsertAfter «Зеленый курсив, размер 20»

.Range(Start:=82, End:=107).Font.Italic = True

.Range(Start:=82, End:=107).Font.Size = 20

.Range(Start:=82, End:=107).Font.ColorIndex = wdGreen

End With

Set myDocument = Nothing

Set myWord = Nothing

Exit Sub

Instr:

If Err.Description <> «» Then

  MsgBox «Произошла ошибка: « & Err.Description

End If

If Not myWord Is Nothing Then

  myWord.Quit

  Set myDocument = Nothing

  Set myWord = Nothing

End If

End Sub

Вы можете запустить эти примеры в редакторе VBA Excel на своем компьютере и посмотреть результаты.

title keywords f1_keywords ms.prod api_name ms.assetid ms.date ms.localizationpriority

Rows.Add method (Word)

vbawd10.chm155975780

vbawd10.chm155975780

word

Word.Rows.Add

d84286cb-42b5-a717-f152-0d9c3f1c6d9c

06/08/2017

medium

Rows.Add method (Word)

Returns a Row object that represents a row added to a table.

Syntax

expression.Add ( _BeforeRow_ )

expression Required. A variable that represents a Rows object.

Parameters

Name Required/Optional Data type Description
BeforeRow Optional Variant A Row object that represents the row that will appear immediately below the new row.

Return value

Row

Example

This example inserts a new row before the first row in the selection.

Sub AddARow() 
 If Selection.Information(wdWithInTable) = True Then 
 Selection.Rows.Add BeforeRow:=Selection.Rows(1) 
 End If 
End Sub

This example adds a row to the first table and then inserts the text Cell into this row.

Sub CountCells() 
 Dim tblNew As Table 
 Dim rowNew As Row 
 Dim celTable As Cell 
 Dim intCount As Integer 
 
 intCount = 1 
 Set tblNew = ActiveDocument.Tables(1) 
 Set rowNew = tblNew.Rows.Add(BeforeRow:=tblNew.Rows(1)) 
 For Each celTable In rowNew.Cells 
 celTable.Range.InsertAfter Text:="Cell " & intCount 
 intCount = intCount + 1 
 Next celTable 
End Sub

See also

Rows Collection Object

[!includeSupport and feedback]

Формулировка задачи:

Добрый день. Ломаю голову над казалось бы элементарной задачей. В документе Word существует таблица, уже сформатированная должным образом. В нее необходимо выгружать данные с листа Excel. Копирование / вставка из ячеек проходит,

но мне при этом нужно добавлять строки в середине таблицы в Worde

.
Делаю так

пробовала

Код к задаче: «Вставка строки в уже существующую таблицу в Word»

textual

Dim tblNew As Table
Dim rowNew As Row
 
Set tblNew = ActiveDocument.Tables(2)
'вставка перед 2ой строкой
Set rowNew = tblNew.Rows.Add(BeforeRow:=tblNew.Rows(2))

Полезно ли:

12   голосов , оценка 3.833 из 5

Using Excel VBA to create Microsoft Word documents

In these examples, we generate Microsoft Word Documents with various formatting features using
the Microsoft Excel VBA scripting language. These techniques can have many useful applications.
For instance if you have a list of data like a price or product list in Excel that you want to present
in a formatted Word Document, these techniques can prove useful.

In these examples, we assume the reader has at least basic knowledge of VBA, so we will not
go over basics of creating and running scripts. This code has been tested on Microsoft Word and Excel
2007. Some changes may be required for other versions of Word and Excel.

Writing to Word
Inserting a Table of Contents
Inserting Tabs
Inserting Tables
Inserting Bullet List
more on Inserting Tables
Multiple Features

Function that demonstrates VBA writing to a Microsoft Word document

The following code illustrates the use of VBA Word.Application object and related properties.
In this example, we create a new Word Document add some text.

    'In Tools > References, add reference to "Microsoft Word XX.X Object Library" before running.
	
    'Early Binding
    Dim wdApp As Word.Application
    Set wdApp = New Word.Application
    
    'Alternatively, we can use Late Binding
    'Dim wdApp As Object
    'Set wdApp = CreateObject("word.Application")
        
    With wdApp
        .Visible = True
        .Activate
        .Documents.Add
        
        With .Selection
            .ParagraphFormat.Alignment = wdAlignParagraphCenter
            .Font.Bold = True
            .Font.Name = "arial"
            .Font.Size = 14
            .TypeText ("My Heading")
            .TypeParagraph            
        End With
    End With 

Some VBA Vocabulary

ParagraphFormat
Represents all the formatting for a paragraph.

output in MS Word:

Inserting a Table of Contents into Word Document using Excel VBA

In this example, we generate a Table of Contents into a Word Document using Excel VBA

Sub sAddTableOfContents()
    
    Dim wdApp As Word.Application
    Set wdApp = New Word.Application
	
    'Alternatively, we can use Late Binding
    'Dim wdApp As Object
    'Set wdApp = CreateObject("word.Application")
    
    Dim wdDoc As Word.Document
    Set wdDoc = wdApp.Documents.Add
    
    ' Note we define a Word.range, as the default range wouled be an Excel range!
    Dim myWordRange As Word.range
    Dim Counter As Integer
    
    wdApp.Visible = True
    wdApp.Activate
    
    'Insert Some Headers
    With wdApp
        For Counter = 1 To 5
            .Selection.TypeParagraph
            .Selection.Style = "Heading 1"
            .Selection.TypeText "A Heading Level 1"
            .Selection.TypeParagraph
            .Selection.TypeText "Some details"
        Next
    End With

    ' We want to put table of contents at the top of the page
	Set myWordRange = wdApp.ActiveDocument.range(0, 0)
    
    wdApp.ActiveDocument.TablesOfContents.Add _
     range:=myWordRange, _
     UseFields:=False, _
     UseHeadingStyles:=True, _
     LowerHeadingLevel:=3, _
     UpperHeadingLevel:=1

End Sub

Some VBA Vocabulary

ActiveDocument.TablesOfContents.Add
The TablesOfContents property to return the TablesOfContents collection.
Use the Add method to add a table of contents to a document.

Some TablesOfContents Parameters

Range The range where you want the table of contents to appear. The table of contents replaces the range, if the range isn’t collapsed.

UseHeadingStyles True to use built-in heading styles to create the table of contents. The default value is True.

UpperHeadingLevel The starting heading level for the table of contents. Corresponds to the starting value used with the o switch for a Table of Contents (TOC) field. The default value is 1.

LowerHeadingLevel The ending heading level for the table of contents. Corresponds to the ending value used with the o switch for a Table of Contents (TOC) field. The default value is 9.

output Word Table in MS Word:

Write Microsoft Word Tabs

A function that writes tabbed content to a Microsoft Word Document. Note in each iteration, we change the
value of the leader character (characters that are inserted in the otherwise blank area created by the tab).

Public Sub sWriteMicrosoftTabs()

    'In Tools > References, add reference to "Microsoft Word XX.X Object Library" before running.
    
    'Early Binding
    Dim wdApp As Word.Application
    Set wdApp = New Word.Application
    
    'Alternatively, we can use Late Binding
    'Dim wdApp As Object
    'Set wdApp = CreateObject("word.Application")
        
    With wdApp
        .Visible = True
        .Activate
        .Documents.Add
    
        For Counter = 1 To 3
            .Selection.TypeText Text:=Counter & " - Tab 1 "
            
            ' position to 2.5 inches
            .Selection.Paragraphs.TabStops.Add Position:=Application.InchesToPoints(2.5), _
                Leader:=Counter, Alignment:=wdAlignTabLeft
            
            .Selection.TypeText Text:=vbTab & " - Tab 2 "
            
            ' position to 5 inches
            .Selection.Paragraphs.TabStops.Add Position:=Application.InchesToPoints(5), _
                Leader:=Counter, Alignment:=wdAlignTabLeft
            
            .Selection.TypeText Text:=vbTab & " - Tab 3 "
                    
            .Selection.TypeParagraph
        Next Counter
        
    End With
End Sub

Some VBA Vocabulary

.TabStops.Add Use the TabStops property to return the TabStops collection. In the example above,
nprogram adds a tab stop positioned at 0, 2.5 and 5 inches.

output in MS Word:

Write Microsoft Word Tables

In this example, we generate a Microsoft Table using Excel VBA

Sub sWriteMSWordTable ()
 
    'In Tools > References, add reference to "Microsoft Word XX.X Object Library" before running.
    
    'Early Binding
    Dim wdApp As Word.Application
    Set wdApp = New Word.Application
    
    'Alternatively, we can use Late Binding
    'Dim wdApp As Object
    'Set wdApp = CreateObject("word.Application")
        
    With wdApp
        .Visible = True
        .Activate
        .Documents.Add
        
        With .Selection
        
            .Tables.Add _
                    Range:=wdApp.Selection.Range, _
                    NumRows:=1, NumColumns:=3, _
                    DefaultTableBehavior:=wdWord9TableBehavior, _
                    AutoFitBehavior:=wdAutoFitContent
            
            For counter = 1 To 12
                .TypeText Text:="Cell " & counter
                If counter <> 12 Then
                    .MoveRight Unit:=wdCell
                End If
            Next
        
        End With
        
    End With

End Sub

Some VBA vocabulary

Table.AddTable object that represents a new, blank table added to a document.

Table.Add properties

Range The range where you want the table to appear. The table replaces the range, if the range isn’t collapsed.

NumRows The number of rows you want to include in the table.

NumColumns The number of columns you want to include in the table.

DefaultTableBehavior Sets a value that specifies whether Microsoft Word automatically resizes cells in tables to fit the cells� contents (AutoFit). Can be either of the following constants: wdWord8TableBehavior (AutoFit disabled) or wdWord9TableBehavior (AutoFit enabled). The default constant is wdWord8TableBehavior.

AutoFitBehavior Sets the AutoFit rules for how Word sizes tables. Can be one of the WdAutoFitBehavior constants.

output in MS Word:

Write Microsoft Word bullet list

In this example, we write with bullet list and outline numbers with Excel VBA

    'In Tools > References, add reference to "Microsoft Word XX.X Object Library" before running.
    
    'Early Binding
    Dim wdApp As Word.Application
    Set wdApp = New Word.Application
    
    'Alternatively, we can use Late Binding
    'Dim wdApp As Object
    'Set wdApp = CreateObject("word.Application")
    
    With wdApp
        .Visible = True
        .Activate
        .Documents.Add
        ' turn on bullets
        .ListGalleries(wdBulletGallery).ListTemplates(1).Name = ""
        .Selection.Range.ListFormat.ApplyListTemplate ListTemplate:=.ListGalleries(wdBulletGallery).ListTemplates(1), _
            continuepreviouslist:=False, applyto:=wdListApplyToWholeList, defaultlistbehavior:=wdWord9ListBehavior
        
        With .Selection
            .ParagraphFormat.Alignment = wdAlignParagraphLeft
            .Font.Bold = False
            .Font.Name = "Century Gothic"
            .Font.Size = 12
            .TypeText ("some details")
            .TypeParagraph
            .TypeText ("some details")
            .TypeParagraph
        End With
        
        ' turn off bullets
        .Selection.Range.ListFormat.RemoveNumbers wdBulletGallery
        
        With .Selection
            .ParagraphFormat.Alignment = wdAlignParagraphLeft
            .TypeText ("some details")
            .TypeParagraph
            .TypeText ("some details")
            .TypeParagraph
            
        End With
        
        ' turn on outline numbers
        .ListGalleries(wdOutlineNumberGallery).ListTemplates(1).Name = ""
        .Selection.Range.ListFormat.ApplyListTemplate ListTemplate:=.ListGalleries(wdOutlineNumberGallery).ListTemplates(1), _
            continuepreviouslist:=False, applyto:=wdListApplyToWholeList, defaultlistbehavior:=wdWord9ListBehavior
        
        With .Selection
            .ParagraphFormat.Alignment = wdAlignParagraphLeft
            .TypeText ("some details")
            .TypeParagraph
            .TypeText ("some details")
            
        End With
        
    End With

output in MS Word:

Another example of Writing Tables to Microsoft Word

In this example we will create a word document with 20 paragraphs. Each paragraph will have a header with a header style element

    
   'In Tools > References, add reference to "Microsoft Word XX.X Object Library" before running.
    Dim wdApp As Word.Application
    Dim wdDoc As Word.Document

    Set wdApp = New Word.Application
    wdApp.Visible = True
    
    
    Dim x As Integer
    Dim y As Integer
    
    wdApp.Visible = True
    wdApp.Activate
    wdApp.Documents.Add
            
    wdApp.ActiveDocument.Tables.Add Range:=wdApp.Selection.Range, NumRows:=2, NumColumns:= _
        2, DefaultTableBehavior:=wdWord9TableBehavior, AutoFitBehavior:= _
        wdAutoFitFixed
                
    With wdApp.Selection.Tables(1)
        If .Style <> "Table Grid" Then
            .Style = "Table Grid"
        End If
        .ApplyStyleHeadingRows = True
        .ApplyStyleLastRow = False
        .ApplyStyleFirstColumn = True
        .ApplyStyleLastColumn = False
        .ApplyStyleRowBands = True
        .ApplyStyleColumnBands = False
    End With
            
    With wdApp.Selection
        
        For x = 1 To 2
            ' set style name
            .Style = "Heading 1"
            .TypeText "Subject" & x
            .TypeParagraph
            .Style = "No Spacing"
            For y = 1 To 20
                .TypeText "paragraph text "
            Next y
            .TypeParagraph
        Next x
    
        ' new paragraph
        .TypeParagraph
        
        ' toggle bold on
        .Font.Bold = wdToggle
        .TypeText Text:="show some text in bold"
        .TypeParagraph
        
        'toggle bold off
        .Font.Bold = wdToggle
        .TypeText "show some text in regular front weight"
        .TypeParagraph
        
        
    End With
        
    

Some VBA vocabulary

TypeText

Inserts specified text at the beginning of the current selection. The selection is turned into an insertion point at the end of the inserted text.
If Options.ReplaceSelection = True then the original selection will be replaced. This behaves exactly the same as typing some text at the keyboard.

TypeParagraph

Insert a new blank paragraph. The selection is turned into an insertion point after the inserted paragraph mark. If Options.ReplaceSelection = True then the original selection will be replaced. This behaves exactly the same as pressing the Enter key.

output in MS Word:

Generating a Word table with VBA
	'In Tools > References, add reference to "Microsoft Word XX.X Object Library" before running.

	Dim wdApp As Word.Application
	Dim wdDoc As Word.Document
	Dim r As Integer

	Set wdApp = CreateObject("Word.Application")
	wdApp.Visible = True

	Set wdDoc = wdApp.Documents.Add
	wdApp.Activate

	Dim wdTbl As Word.Table
	Set wdTbl = wdDoc.Tables.Add(Range:=wdDoc.Range, NumRows:=5, NumColumns:=1)

	With wdTbl

		.Borders(wdBorderTop).LineStyle = wdLineStyleSingle
		.Borders(wdBorderLeft).LineStyle = wdLineStyleSingle
		.Borders(wdBorderBottom).LineStyle = wdLineStyleSingle
		.Borders(wdBorderRight).LineStyle = wdLineStyleSingle
		.Borders(wdBorderHorizontal).LineStyle = wdLineStyleSingle
		.Borders(wdBorderVertical).LineStyle = wdLineStyleSingle
		
		For r = 1 To 5
			.Cell(r, 1).Range.Text = ActiveSheet.Cells(r, 1).Value
		Next r
	End With

	

output in MS Word:

Option Explicit
Dim wdApp As Word.Application
 
Sub extractToWord()

   'In Tools > References, add reference to "Microsoft Word 12 Object Library" before running.
   
    Dim lastCell
    Dim rng As Range
    Dim row As Range
    Dim cell As Range
    Dim arrayOfColumns
    arrayOfColumns = Array("", "", "", "", "", "", "", "", "", "", "", "", "", "", "")
    Dim thisRow As Range
    Dim thisCell As Range
    Dim myStyle As String
    
    ' get last cell in column B
    lastCell = getLastCell()
    
    Set rng = Range("B2:H" & lastCell)
    
    'iterate through rows
    For Each thisRow In rng.Rows
            
        'iterate through cells in row row
        For Each thisCell In thisRow.Cells

            If thisCell.Value = arrayOfColumns(thisCell.Column) Or thisCell.Value = "" Then
            ' do nothing
                ''frWriteLine thisCell.Value, "Normal"
                ''frWriteLine arrayOfColumns(thisCell.Column), "Normal"
                  If thisCell.Value = arrayOfColumns(thisCell.Column) Or thisCell.Value = "" Then
                  End If
                  
            Else
                myStyle = "Normal"
                Select Case thisCell.Column
                    Case 2
                        myStyle = "Heading 1"
                    Case 3
                        myStyle = "Heading 2"
                    Case 4
                        myStyle = "Heading 3"
                    Case Is > 5
                        myStyle = "Normal"
                    
                End Select
                    
                frWriteLine thisCell.Value, myStyle
            End If
        
        arrayOfColumns(thisCell.Column) = thisCell.Value
    
      Next thisCell
    Next thisRow
    
End Sub

Public Function getLastCell() As Integer

    Dim lastRowNumber As Long
    Dim lastRowString As String
    Dim lastRowAddress As String
         
    With ActiveSheet
        getLastCell = .Cells(.Rows.Count, 2).End(xlUp).row
    End With
    
End Function

Public Function frWriteLine(someData As Variant, myStyle As String)
    
    If wdApp Is Nothing Then
        
        Set wdApp = New Word.Application
        With wdApp
            .Visible = True
            .Activate
            .Documents.Add
        End With
            
    End If
    
    With wdApp
        
        With .Selection
            .ParagraphFormat.Alignment = wdAlignParagraphCenter
            .Style = myStyle
            .TypeText (someData)
            .TypeParagraph
        End With
    End With
    
End Function

output in MS Word:

������ � ������� � Word VBA

������ � ������� � Word VBA

������� Range � Selection �������� ���������� ������� ��� ����������� ����� ��������, ������� �� ������� ��������� � ������� � ������� Word VBA. ��������� �� ���� �������� ����� ��������� � ���������� � �����, �� � ����� ������ ��� ��������� �������� ��� ���������� �������, ������ ��� ������� ���������.

� �������� Range � Selection ���������� ����� ������, �� ���� � ��������� �������� �������. ��� ������� ������������ ����������� ������������������ ��������, ��� �������� �� ������� ��������� ��������� ��������. ��� ������� ����� ����� ����� ������� � �������. ������ ��������� �������� � ������ ��������� ��� ���������� ��������, � ������ — ��� ����������. ������������ �������� ������� � � ���, ��� ������ Selection ������������� ��������� � ������� ����: ������, ������������ ����������� ��� ������ ������� �������, � �� ����� ��� ������� Range ���������� ���������� �� ���������� ������� � ������ �������� �����.

����������� ������ Selection � ��� ������, ���� ���� ��������� ������� �� ������������, ��������, �� ������ ������� �����, � ������� ����� ��������� ������������ ��������, ��� � ��� ������, ���� ��� ���������� �������� ������������, ����� ������ ����� ����� �������. � ������ ��������� ������� ����� �������� ������� Range. ��� ������������ ������� �������� ���������� �������� � ������ ���������� ������������: Word ��������� ���������� ������ ��� ������ ��������� ����������� ���������� �������, � ��� ��������� ��������� ���������� ������ �� �����������. ����� ����, ��������� ���������� �� ���������� �� ���������� ��������, ��������� �������������.

�������� �� �� ��������, ������� Selection � Range ����� ��������� ���� �� �������. ��� ����������� ����������� ����������� ������, ��� ��� ������ ������� �������������� �������� ������ � �����������. � ����������������� �����, ������������ ������ ���������� ���������� ��������� ������������- �������� ���. ����������� ��������� ������� ������.

* ��� ��������� ��������� ������������ ��� ����� Select. ��������, ��� ������� RangeR ������� ����� ��� RangeR. Select.

* ��� ��������� ������� � ���������, ��������������� �� �� ����������, ��� � ���������� �������, ������������ �������� Range.

�������: ���� �����, ����������� � ��������� ������, ���������� ��� ���������, � �� ������ ��������� ��� � ���������� �������, ������ �������� � ���� ��� ���������� Selection . Range . ���������.

Word VBA ���������� ����� ��� ������� ��� ����������� � ��������� �������� ���������� � ���������� ��������. � ��������� ������� � ������������ ������ ����� ������ �� ���; ��� ���������� � ������� �������� ��� �������� ���������� � ���������� �������.

����� Expand ����������� ������������ �������� ��� ���������� �������, �������� ���� ������ � �� �����. ���� ����� ������������ ����� ������, �����, ����� ��� ���-������ ������. �� ������ �������� ������ ���� ������� ������������ ����; ����� ����, ���������� �������� ������ � ������ ��������� ��� ���������� ������� �� �����������.

��� ���������� � ���������� ������� �����, ������� ����� ��������� ����� �� ���, ����������� ����� ����������:

Selection.Expand(wdWord)

�� ������ ������������ ����� �� ��������� �������� ��� ���������� �������; wdCharct er, wdWord, wdSent ence, wdParagraph, wdSection, wdStory, wdCell, wdColumn, wdRow, wdTable � (������ ��� �������� Selection) wdLine. �� ��������� ������������ ��������� wdWord.

������ ��� ������� ������������ �� ����� ���������� �������: ������� Selection (�� �� ���������) ����� �������� ����� Expand. ���� ����� �������� ��������������� �������� Word, ������� ��������� ��������� ���������� ������� ��� ����������� ��������� ����. ������ ���, ����� ��������� �������� ����� Extend, ���������� ������� ������������� �� ���� ������, ������� ������� ����� �� ������ �������: ������� �����, �����������, �����, ���������� �������� ��� ����� ��������. ���� �� ������� �������� � ���� ������ �������, ��������, Selection.Expand ( «�» ). ���������� ������� ����� ��������� ������ �� ������� �������������� ���������� �������.

Word VBA ��������� ��� �������� ���������� ������ � ����� ��������� ��� ���������� �������. ������ ������ � ����, ��� ������, � ����� ������� ������������ ����� Move, �������� ������������ ��������� ��� ���������� �������: ��� �� ���������� �����, ������� ���������� � ��������� �������.

����� Move �������� �������� ��� ���������� �������, ������� � �� ������, ������� �� ������������, � � ��� ��� ��� �������� ������. ������������ ��������� � ������� ��������� �������. ����� ����� ����� Move ���������� «������» ������ � ������������ � ������ ������������. �� ��������� ����������� �� ������ ������������ ������ Expand � Mover,nd ��� ���������� ������� �������.

����������� ���� ������ ���������� ����������� �������� � ��������� �� ��� ������ �����. �������� �������� �� ��, ��� �� ����������� ����������� ��������� � �������� �������� ��������� Uni t (������ ���� ���������� ����������� �������� �������� � �������

«���������� ���������� � ���������� ��������» ������ � ���� �����). �������� Count ������������ ����� ����� ������������� �����, ���� �� ������ ���������� ������ ������ �� ��������� (�.�. � ��� �����), ��� �������������, ���� �� ������ ���������� ������ ����� �� ���������. � ����������� ���� ������� ��������� �� ��������� � ������, ��������� ������������ ������� �������� (���������� ������������ ���������) ����� �� ������������:

oTheRange .Move Unit : = waParagraph, Count, : = -2

������ MoveStart. � MoveEnd �������� ����������� ��� ��, ��� � ����� Move, ������ ��� �������� ��������� ��� �������� ����� ��������� ��� ���������� ������� ��������������. ����������� ���� ���������� ���������� ������ ���������� ������� �� ��� ����� ����� � ����� ���������:

Select-on.KoveStart Unit : = wdWord, Count := 3

�������� �������� �� ��, ��� ���� �� ����������� ��������� ����� ������� � �����, Word ������ �������� ��� ���������� ������� � ���������� �� � ������������ � ���������� ������������.

��� ���� ���� �������, Start Of ��� EndOf, ���������� ��� ��������� ������ ��� ����� ��������� ��� ���������� �������. ����� Start Of ���������� ������ ������� ������� � ������ �������� �����, � �� ����� ��� ����� EndOt ���������� ����� ������� ������ � ����� �������� �����.

�� ������ ������������ �������� Extend � ����� ������� ��� �������� ��� ���������� Word. ���� ������������ ������� ������� ��� ��������� � ���� ����, � �������� �� ��������� �� �����������, ����� �� ����������. ����������� ��������� wdMove ��� �������� ������� ��� ��������� wdExtend ��� ����������� ������ ��������� �������. ���� �������� ��������������� ������:

Selection. Start Of Unit := wdSentence, Extend := wdMove

����� ����� ��� ���������� ����� �������� ��� ���������� ������� � �����, ������� �� �������� �������� ������. � ����������� ����� ������ ��������� �������� ��� ���������� ������� — ��� ����� �������� ��� ���������� �������, ��������� � �������� ����� ������� ���������. ������ �������� �������� ����������� ������ � ��� ���������, ����� ��� ���������� �������� ����, ������� ��� ������ ������� �� ��� ����� ���������� ������� ��� ���������, �������� ��� ������ ������. (�� ������ �������� ������� �����, ����� ������, � ����� ��������� ������ �������� � «��������» �������� ��� ���������� �������).

����������� ����� Collapse ��� ������ ��������� ��� ���������� �������. �� ������ ����� ������ � ��� ��������� ��� �������� �����, ��������� �������������� �������� Direction. ����������� ���� ���������� ������� ���������� ������� � �� ��������� �����:

Selection.Collapse

� ���� ������ ������� ���������� ������� � �� �������� �����:

Selection.Collapse( Direction:=wdCollapseEnd)

���� �� ������� ��������, ������� ������������� ������ ������, � ��� �������� ����� (��������� ��������� wdCollapseEnd), Word ��������� ������ �������� ����� ����� ������ (��� ��������, ��� ������ �������� ����� ���������� � ��������� ������). ���� �� �� ������ ���������� ���-�� ����� ������ ������ ��������� ���������, �� ������ ������� ����������� �������� ������� � ������� ������ MoveEnd, ��������� ����������, �������� ����:

��������.MoveEnd Unit := wdCharacter, Count := -1

������� ���� ����� � ��������� ��� ���������� ������� ������ ��������: ������ ����������� ����� Delete ���������������� �������. �� ������ ������������ � ����� Cut, ���� ������ ������� ����� � ��������� ��� � ����� ������. ������� ��, ����� ���� �������� ����� � ����� ������, �� ������ ������� �� ����� � ��������� ��� ���������� �������.

�� ������ �������� �����, ������ ���������� � ����� ������, � ����� �������� ��� ���������� �������, ���������������� ������� Paste ����� �������. ���� ������ ���������� ��� �� ����, ����������� ����� ������ ������� �������� ����� � �������, ����� ��� �� ��� ��� ���������� ����� ���������� ������� �������� � Word.

���� ������������� ������ ������ ��� �������� ������ �� ������ ����� � ������ ������� ������ ���������, ���� ����� �� ������ ����������� ����� �����������. ������� ������� ������������ �������� Text ��� FormattedText ��������� ��� ���������� �������. ������� ��� �������� ������� ��������� ��� ���������� �������, ���������� �����, ������� �� ������ ��������, � ���. ������ ���������� ������ ���� ���� �� ��� ���, ���� ������������ ����� �� ������ ����� �������� ������������ ����� � �������.

����������� ���� �������� ���� �������� ����� �� ���������� ������� � ������ ��������, ����������� � �������� (�������� �������� ����������� ��������� ������ ����). � ����� ����� ������������ �������� ������ ��� �����; ����� �������������� ��� ���� ��������:

With ActiveDocument.Bookmarks("TheBookmark")

Set RangeY = _

ActiveDocument.Range(Start:=.Start, End=.Start)

End With

RangeY.Text = Selection.Text

��� �������� ������ � ������� � ��� �������������� ������ �������� �������� Text ��������� FormattedText.

���������� ��� ����������� ������� ���������� ������ �������� ������� �������� Text ��������� ��� ���������� ������� ������ ������, ������� �� ������ ��������. ��� ����������������� �� �������, ���������� ����:

Range2.Text = «��, ��! � ���� ����-�� ������ ���!»

������ ���������, ��� ������������� �������� Text �������� � ������ ������ ������������� � �������. �� ��������� ����� (���� ������ �� ������������� �� ������ �������� ������������ �����), ������� ������� ������.

����������� ������ Insert Before ��� Insert After �������� Range ��� Selection ��� ������� ������ � ������������ ����� ���������, �� ���������� ��� ���� ������������ �����. ��� ������ ��������� �������� ����� ����� ��������������� ����� ��� ����� ���������� ������� ��������������. Word �������� ����������� ����� � ���������� ������� ��� ��������.

��� ������������� ������ �� ������� ������������ ���������� �������� �����, ������� �� ������ ��������. ����������� ���� �������� ���� ��������� ����� �����, ���������� ����� Dairy Entry � ������ ���������� ������� (�������� �������� �� ������������� ����� ��������� VBA, ��� vbCr, ��� ���������� ����� ������). ����� ����� � ����� ����������� ����� �����, ������� ���������� � ������� ����. ���� �� �������� ����� ����� �� ���������� ����� ����, �����, ���������� ������� ����, �������� ����� ����� ������ � ���������� �������.

Dim strInsert Text As String

Selection.Insert Before "Dairy Entry" & vbCr

strInsert Text = "Today" & Chr(146) & "s date is"

strInsertText = _

strInsertTex't & Format (Now, "Long date") & ". "

Selection.InsertAfter strInsertText & vbCr

���� ������ ����������, ����� ������� ����������� ����� ����� ��������� ��������� ���������� ������� VBA, ������������ ��������� ��������, � ����� �������� � ��������� VBA. ��������� �������� � �������������� � ��������� ��������� �������� � ������� VBA �������� � ����� 11.

���������� ������ �������� ����� ������ ����� � �������� — �������� ���� ������ (�������������� ���������� vbCr) � ������� �������� Text ��� ������� Insert Before ��� Insert After. ����� Add, ����������� � ���������� Paragraphs, ��������, �� �� ����� ������ � ����������.

����������� ��� � ��� ������, ���� ��� ���������� ���������� ����� ����� � ��������� ��� ���������� �������, � �� � �� ������ ��� �����.

��������� ������� ��������� ��� ���������� ������� — ��� ��� ���� � ��������� �������� ���� ������. ��� ��� �������� ������������� �������� �� ���� ������ ��������� Word � ������������� ��������� �������.

��� ��������

������������� ������ �…

Font

��������������� �������� ������� ������� �������������� ��������, ����� ��� Name, Size � Bold. �� ��������� �������� �� ������ �������� ���������������� ������ � ����� ������ ��������� �������������� �������� Range, �� ��������� � �������� Font, �� ������ �� ��� ������ � ����������� ���������

Paragrap

��������������� �������� ������� ������� �������������� �������, ����� ��� hFormat LeftIndent ��� LineSpacing

Style

��� ����� ������� ��� ������, ������������ � ��������� ��� ���������� �������

Borders

������� ������ ������

Tabstops

���� � ������������ ����� ���������. �� ������ �������� ������ � ���� ��������� ������ � ������� �������� Paragraph, � �� ��������������� ����� ��������� ��� ���������� �������

Понравилась статья? Поделить с друзьями:
  • Как в word записать степень числа
  • Как в word изменить книжную страницу на альбомную
  • Как в word записать пример
  • Как в word изменить заглавные буквы на строчные буквы на клавиатуре
  • Как в word заморозить