Передать в таблицу word vba

Вставка таблицы Excel в документ Word с помощью кода VBA Excel. Метод Selection.PasteExcelTable: синтаксис, параметры, пример использования.

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

Метод Selection.PasteExcelTable

Метод Range.Paste, использующийся в VBA Word для вставки в документ таблиц, скопированных в буфер обмена из другого документа Word, не применим для вставки в документ таблиц, скопированных из книги Excel. Для этих целей используется метод Selection.PasteExcelTable.

Selection.PasteExcelTable — это метод, предназначенный для вставки Excel-таблицы из буфера обмена в документ Word и ее форматирования в соответствии с заданными параметрами.

Синтаксис

Expression.PasteExcelTable(LinkedToExcel, WordFormatting, RTF)

Expression — переменная, представляющая объект Selection. В том числе, это может быть курсор или закладка.

Параметры

Все параметры метода Selection.PasteExcelTable логического типа и являются обязательными.

Параметр Описание
LinkedToExcel True — вставленная таблица связывается с исходным файлом Excel, чтобы изменения, внесенные в файл Excel, отображались в Microsoft Word.
False — связь между вставленной таблицей и таблицей в исходном файле не устанавливается.
WordFormatting True — вставленная таблица будет отформатирована как таблица документа Word.
False — вставленная таблица будет отформатирована в соответствии с исходным файлом Excel.
RTF True — Excel-таблица будет вставлена в расширенном текстовом формате (RTF).
False — Excel-таблица будет вставлена в формате HTML-таблицы.

Допустим, у нас есть таблица Excel, начинающаяся с ячейки A1 (или с любой другой), и нам необходимо скопировать эту таблицу в существующий документ Word, вставив ее на место закладки «Закладка1».

Решение:

Sub Primer()

Dim myWord As New Word.Application, myDoc As Word.Document

‘Открываем существующий документ Word

Set myDoc = myWord.Documents.Open(«C:ТестоваяДокумент1.docx»)

‘Копируем таблицу на активном листе в буфер обмена

‘Вместо ячейки Range(«A1») можно указать любую другую, расположенную внутри таблицы

Range(«A1»).CurrentRegion.Copy

‘Вставляем таблицу из буфера обмена на место закладки

myDoc.Bookmarks(«Закладка1»).Range.PasteExcelTable False, False, False

‘Отображаем программу Word

myWord.Visible = True

‘Очищаем переменные

Set myWord = Nothing

Set myDoc = Nothing

End Sub

Если необходимо таблицу вставить в конец документа, строку

myDoc.Bookmarks(«Закладка1»).Range.PasteExcelTable False, False, False

следует заменить на

With myDoc

    ‘Переводим курсор в конец документа

    .Range(.Range.Characters.Count 1, .Range.Characters.Count 1).Select

    ‘Добавляем перенос строки, если необходимо

    .ActiveWindow.Selection.InsertAfter vbCr

    ‘Переводим курсор в конец документа

    .Range(.Range.Characters.Count 1, .Range.Characters.Count 1).Select

    ‘Вставляем таблицу из буфера обмена

    .ActiveWindow.Selection.PasteExcelTable False, False, False

End With


T-viRUS-161

1 / 1 / 0

Регистрация: 27.05.2014

Сообщений: 23

1

16.11.2017, 20:07. Показов 2194. Ответов 4

Метки нет (Все метки)


Студворк — интернет-сервис помощи студентам

Здравствуйте Уважаемые форумчане!
Для переноса данных из Excel’я в Word использую макрос с циклом перебора ячеек

Visual Basic
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Dim oWApp As Word.Application
Dim oWDoc As Word.Document
Dim oWTbl As Word.Table
Dim tRange As Range
 
With ThisWorkbook.Sheets("лист")
Set oWApp = CreateObject("Word.Application")
oWApp.Visible = True
Set oWDoc = oWApp.Documents.Open(ThisWorkbook.Path & "123.dot")
Set tRange = .Range("C1:F" & .Range("F" & .Rows.Count).End(xlUp).Row) 'данные для таблицы в Ворде
Set oWTbl = oWDoc.Tables.Add(oWDoc.bookmarks("таблица").Range, tRange.Rows.Count, tRange.Columns.Count) 'создаю таблицу по закладке
 
здесь использую цикл перебора всех ячеек
 
End With

Когда ячеек очень много (за 1000) то данные вносятся очень долго, порой уходит 2 секунды на ячейку. Есть ли еще способы вставки таблицы? Буфер обмена использовать не могу, т.к. в это время я копирую/вырезаю файлы другим макросом.



0



15136 / 6410 / 1730

Регистрация: 24.09.2011

Сообщений: 9,999

16.11.2017, 21:34

2

Цитата
Сообщение от T-viRUS-161
Посмотреть сообщение

здесь использую цикл перебора всех ячеек

Самое-то важное, что влияет на скорость, и не привели
Можно например экспортировать как txt, разделитель табуляция, а в Ворд импортировать методом Вставка — Объект — Текст из файла, и преобразовать в таблицу. Может быстрее будет.



0



T-viRUS-161

1 / 1 / 0

Регистрация: 27.05.2014

Сообщений: 23

16.11.2017, 21:50

 [ТС]

3

Цитата
Сообщение от Казанский
Посмотреть сообщение

Самое-то важное, что влияет на скорость, и не привели

2 цикла. Решил спросить знатоков, может кто иначе делает?

PureBasic
1
2
3
4
5
6
7
For r = 1 To tRange.Rows.Count '
For c = 1 To tRange.Columns.Count '
 
oWTbl.Cell(r, c).Range = tRange.Cells(r, c)
 
Next c
Next r



0



Казанский

15136 / 6410 / 1730

Регистрация: 24.09.2011

Сообщений: 9,999

16.11.2017, 23:19

4

T-viRUS-161, чет я перемудрил насчет файла. Можно собрать содержимое диапазона в текстовую переменную, вставить в Ворд, преобразовать в таблицу:

Visual Basic
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
'сбор содержимого диапазона в переменную s
Dim s$, d$, v(), i&, j&
  With ThisWorkbook.Sheets("лист")
    v = .Range("C1", .Cells(Rows.Count, "F").End(xlUp)).Value
  End With
  For i = 1 To UBound(v)
    d = vbNullString
    For j = 1 To UBound(v, 2)
      d = d & vbTab & v(i, j)
    Next
    s = s & vbCr & Mid$(d, 2)
  Next
  
  Set oWApp = CreateObject("Word.Application")
  oWApp.Visible = True
  Set oWDoc = oWApp.Documents.Open(ThisWorkbook.Path & "123.dot") 'может лучше Documents.Add, коль скоро это шаблон?
 
'вставка текста, преобразование в таблицу
  With oWDoc.bookmarks("таблица").Range
    .InsertAfter Mid(s, 2)
    .ConvertToTable Separator:=1, AutoFit:=True '1=wdSeparateByTabs
  End With



1



T-viRUS-161

1 / 1 / 0

Регистрация: 27.05.2014

Сообщений: 23

16.11.2017, 23:42

 [ТС]

5

Цитата
Сообщение от Казанский
Посмотреть сообщение

Можно собрать содержимое диапазона в текстовую переменную

А «выдержит ли» переменная огромного объема информации? Я пробовал засунуть диапазон в массив и «ConvertToTable» обратно-тоже долго.
Самое интересное что Copy, Past работают намного быстрее.

PureBasic
1
2
tRange.Copy
oWDoc.bookmarks("таблица").Range.PasteExcelTable False, False, False



0



Sub ExcelRangeToWord()

‘PURPOSE: Copy/Paste An Excel Table Into a New Word Document
‘NOTE: Must have Word Object Library Active in Order to Run _
  (VBE > Tools > References > Microsoft Word 12.0 Object Library)

‘SOURCE: www.TheSpreadsheetGuru.com

Dim tbl As Excel.Range
Dim WordApp As Word.Application
Dim myDoc As Word.Document
Dim WordTable As Word.Table

‘Optimize Code
  Application.ScreenUpdating = False
  Application.EnableEvents = False

‘Copy Range from Excel
  Set tbl = ThisWorkbook.Worksheets(Sheet1.Name).ListObjects(«Table1»).Range

‘Create an Instance of MS Word
  On Error Resume Next

        ‘Is MS Word already opened?
      Set WordApp = GetObject(class:=»Word.Application»)

        ‘Clear the error between errors
      Err.Clear

    ‘If MS Word is not already open then open MS Word
      If WordApp Is Nothing Then Set WordApp = CreateObject(class:=»Word.Application»)

        ‘Handle if the Word Application is not found
      If Err.Number = 429 Then
        MsgBox «Microsoft Word could not be found, aborting.»
        GoTo EndRoutine
      End If

  On Error GoTo 0

  ‘Make MS Word Visible and Active
  WordApp.Visible = True
  WordApp.Activate

    ‘Create a New Document
  Set myDoc = WordApp.Documents.Add

  ‘Copy Excel Table Range
  tbl.Copy

‘Paste Table into MS Word
  myDoc.Paragraphs(1).Range.PasteExcelTable _
    LinkedToExcel:=False, _
    WordFormatting:=False, _
    RTF:=False

‘Autofit Table so it fits inside Word Document
  Set WordTable = myDoc.Tables(1)
  WordTable.AutoFitBehavior (wdAutoFitWindow)

   EndRoutine:
‘Optimize Code
  Application.ScreenUpdating = True
  Application.EnableEvents = True

‘Clear The Clipboard
  Application.CutCopyMode = False

End Sub

In this part of the code we are determining if Microsoft Word is open or not.  If Word is already open, we can set a variable equal to the entire program by using GetObject.  If MS Word is not currently running we can use CreateObject to run an instance of Word and then set a variable equal to that specific instance of MS Word.

When using CreateObject, the target application will start running but it is not visible on screen.  Therefore we need to turn the Visible setting on (equal to true).  Also, VBA with Word is a little bit different than with Excel in that it is much more dependent on its window showing on screen.  Therefore a second command must be written to Activate Microsoft Word.

Copy From Excel, Paste Onto Document

Now that you have a new document created, you can command Excel to paste your table into MS Word.  Near the beginning of the code, there was a line that allowed you to specify the exact table you wanted to copy.  The variable tbl was used to remember this table range and to allow you to reference the range later on in the code.  

Guru Tip: It is a good idea to place code that may need to be manually changed at some point in the future near the beginning of the subroutine.  This prevents you from having to scroll through your code and pinpoint the exact place where you spelled out which range you wanted to copy or which worksheet you wanted to pull data from.  This can save you a bunch of time and prevent confusion!

Word has a special method called PasteExcelTable, which (as you can guess) allows you paste in an Excel table.  There are three variables you can tweak to get you table looking and functioning just the way you want.

  • LinkedToExcel True links the pasted table to the original Excel file so that changes made to the Excel file are reflected in Microsoft Word.

  • WordFormatting True formats the table using the formatting in the Word document.  False formats the table according to the original Excel file.

  • RTF True pastes the Excel table using Rich Text Format (RTF).  False pastes the Excel table as HTML.

Now for the last step!  Depending on how large your table is, it may be spilling outside of your document page.  In order to prevent this from happening you can go ahead and use AutoFitBehavior to resize the table to fit perfectly inside your Word document.

About The Author

Hey there! I’m Chris and I run TheSpreadsheetGuru website in my spare time. By day, I’m actually a finance professional who relies on Microsoft Excel quite heavily in the corporate world. I love taking the things I learn in the “real world” and sharing them with everyone here on this site so that you too can become a spreadsheet guru at your company.

Through my years in the corporate world, I’ve been able to pick up on opportunities to make working with Excel better and have built a variety of Excel add-ins, from inserting tickmark symbols to automating copy/pasting from Excel to PowerPoint. If you’d like to keep up to date with the latest Excel news and directly get emailed the most meaningful Excel tips I’ve learned over the years, you can sign up for my free newsletters. I hope I was able to provide you with some value today and I hope to see you back here soon!

— Chris
Founder, TheSpreadsheetGuru.com

Add Table to Word Document

This simple macro will add a table to your Word document:

Sub VerySimpleTableAdd()
    Dim oTable As Table
    Set oTable = ActiveDocument.Tables.Add(Range:=Selection.Range, NumRows:=3, NumColumns:=3)
End Sub

Select Table in Word

This macro will select the first table in the active Word document:

Sub SelectTable()
'selects first table in active doc
    If ActiveDocument.Tables.Count > 0 Then    'to avoid errors we check if any table exists in active doc
        ActiveDocument.Tables(1).Select
    End If
End Sub

Loop Through all Cells in a Table

This VBA macro will loop through all cells in a table, writing the cell count to the cell:

Sub TableCycling()
' loop through all cells in table
    Dim nCounter As Long    ' this will be writen in all table cells
    Dim oTable As Table
    Dim oRow As Row
    Dim oCell As Cell

    ActiveDocument.Range.InsertParagraphAfter    'just makes new para athe end of doc, Table will be created here
    Set oTable = ActiveDocument.Tables.Add(Range:=ActiveDocument.Paragraphs.Last.Range, NumRows:=3, NumColumns:=3)    'create table and asign it to variable
    For Each oRow In oTable.Rows    ' outher loop goes through rows
        For Each oCell In oRow.Cells    'inner loop goes
            nCounter = nCounter + 1    'increases the counter
            oCell.Range.Text = nCounter    'writes counter to the cell
        Next oCell
    Next oRow

    'display result from cell from second column in second row
    Dim strTemp As String
    strTemp = oTable.Cell(2, 2).Range.Text
    MsgBox strTemp
End Sub

Create Word Table From Excel File

This VBA example will make a table from an Excel file:

Sub MakeTablefromExcelFile()
'advanced
    Dim oExcelApp, oExcelWorkbook, oExcelWorksheet, oExcelRange
    Dim nNumOfRows As Long
    Dim nNumOfCols As Long
    Dim strFile As String

    Dim oTable As Table    'word table
    Dim oRow As Row    'word row
    Dim oCell As Cell    'word table cell
    Dim x As Long, y As Long    'counter for loops

    strFile = "c:UsersNenadDesktopBookSample.xlsx"    'change to actual path
    Set oExcelApp = CreateObject("Excel.Application")
    oExcelApp.Visible = True
    Set oExcelWorkbook = oExcelApp.Workbooks.Open(strFile)    'open workbook and asign it to variable
    Set oExcelWorksheet = oExcelWorkbook.Worksheets(1)    'asign first worksheet to variable
    Set oExcelRange = oExcelWorksheet.Range("A1:C8")
    nNumOfRows = oExcelRange.Rows.Count
    nNumOfCols = oExcelRange.Columns.Count

    ActiveDocument.Range.InsertParagraphAfter    'just makes new para athe end of doc, Table will be created here
    Set oTable = ActiveDocument.Tables.Add(Range:=ActiveDocument.Paragraphs.Last.Range, NumRows:=nNumOfRows, NumColumns:=nNumOfCols)    'create table and asign it to variable
    '***real deal, table gets filled here
    For x = 1 To nNumOfRows
        For y = 1 To nNumOfCols
            oTable.Cell(x, y).Range.Text = oExcelRange.Cells(x, y).Value
        Next y
    Next x
    '***
    oExcelWorkbook.Close False
    oExcelApp.Quit
    With oTable.Rows(1).Range    'we can now apply some beautiness to our table :)
        .Shading.Texture = wdTextureNone
        .Shading.ForegroundPatternColor = wdColorAutomatic
        .Shading.BackgroundPatternColor = wdColorYellow
    End With
End Sub

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

Уважаемые ГУРУ, в Excel док-е имеется лист с данными, которые необходимо добавлять в таблицу. Проблема собственно в том, что при копировании данных нужно использовать Range и в моем коде при попытке перейти на следующую строку выставляется символ каретки. Таким образом записи делаются в одной ячейке таблицы. Вот код, пожалуйста укажите на ошибки.

P/s RangeWD объявленна глобально как объект

Код к задаче: «Запись в таблицу Word из Excel»

textual

        RangeWD.Text = Range("C2")
        For Each Range4 In Range("C3", Cells(Rows.Count, "C").End(xlUp))
            WordDoc.Tables(4).Rows.Add
            WordDoc.Tables(4).Cell(i, 1).Range.Text = Range4
            i = i + 1
        Next

Полезно ли:

10   голосов , оценка 3.900 из 5

Понравилась статья? Поделить с друзьями:
  • Передаточный акт в excel
  • Перед числами в excel стоит апостроф
  • Перед формулой excel знак
  • Перед построением секторной диаграммы в excel необходимо нмо
  • Перед игроками лежит куча камней excel