Convert to table word vba

expression.ConvertToTable(Separator, NumRows, NumColumns, InitialColumnWidth, Format, ApplyBorders, ApplyShading, ApplyFont, ApplyColor, ApplyHeadingRows, ApplyLastRow, ApplyFirstColumn, ApplyLastColumn, AutoFit, AutoFitBehavior, DefaultTableBehavior)

expression    Required. An expression that returns a Range or Selection object.

Separator    Optional Variant. Specifies the character used to separate text into cells. Can be a character or one of the following WdTableFieldSeparator
constant. If this argument is omitted, the value of the DefaultTableSeparator property is used.

WdTableFieldSeparator can be one of these WdTableFieldSeparator constants.
wdSeparateByCommas
wdSeparateByDefaultListSeparator
wdSeparateByParagraphs
wdSeparateByTabs

NumRows    Optional Variant. The number of rows in the table. If this argument is omitted, Microsoft Word sets the number of rows, based on the contents of the range or selection.

NumColumns    Optional Variant. The number of columns in the table. If this argument is omitted, Word sets the number of columns, based on the contents of the range or selection.

InitialColumnWidth    Optional Variant. The initial width of each column, in points. If this argument is omitted, Word calculates and adjusts the column width so that the table stretches from margin to margin.

Format    Optional Variant. Specifies one of the predefined formats listed in the Table AutoFormat dialog box (Table menu). Can be one of the WdTableFormat
constants.

Can be one of the following WdTableFormat constants:
wdTableFormat3DEffects1
wdTableFormat3DEffects2
wdTableFormat3DEffects3
wdTableFormatClassic1
wdTableFormatClassic2
wdTableFormatClassic3
wdTableFormatClassic4
wdTableFormatColorful1
wdTableFormatColorful2
wdTableFormatColorful3
wdTableFormatColumns1
wdTableFormatColumns2
wdTableFormatColumns3
wdTableFormatColumns4
wdTableFormatColumns5
wdTableFormatContemporary
wdTableFormatElegant
wdTableFormatGrid1
wdTableFormatGrid2
wdTableFormatGrid3
wdTableFormatGrid4
wdTableFormatGrid5
wdTableFormatGrid6
wdTableFormatGrid7
wdTableFormatGrid8
wdTableFormatList1
wdTableFormatList2
wdTableFormatList3
wdTableFormatList4
wdTableFormatList5
wdTableFormatList6
wdTableFormatList7
wdTableFormatList8
wdTableFormatNone
wdTableFormatProfessional
wdTableFormatSimple1
wdTableFormatSimple2
wdTableFormatSimple3
wdTableFormatSubtle1
wdTableFormatSubtle2
wdTableFormatWeb1
wdTableFormatWeb2
wdTableFormatWeb3

ApplyBorders    Optional Variant. True to apply the border properties of the specified format.

ApplyShading    Optional Variant. True to apply the shading properties of the specified format.

ApplyFont    Optional Variant. True to apply the font properties of the specified format.

ApplyColor    Optional Variant. True to apply the color properties of the specified format.

ApplyHeadingRows    Optional Variant. True to apply the heading-row properties of the specified format.

ApplyLastRow    Optional Variant. True to apply the last-row properties of the specified format.

ApplyFirstColumn    Optional Variant. True to apply the first-column properties of the specified format.

ApplyLastColumn    Optional Variant. True to apply the last-column properties of the specified format.

AutoFit    Optional Variant. True to decrease the width of the table columns as much as possible without changing the way text wraps in the cells.

AutoFitBehavior    Optional Variant. Sets the AutoFit rules for how Word sizes a table. Can be one of the following WdAutoFitBehavior
constant. If DefaultTableBehavior is wdWord8TableBehavior, this argument is ignored.

WdAutoFitBehavior can be one of these WdAutoFitBehavior constants.
wdAutoFitContent
wdAutoFitFixed
wdAutoFitWindow

DefaultTableBehavior    Optional Variant. Sets a value that specifies whether Microsoft Word automatically resizes cells in a table to fit the contents (AutoFit). Can be one of the following WdDefaultTableBehavior
constant.

WdDefaultTableBehavior can be one of these WdDefaultTableBehavior constants.
wdWord8TableBehavior Disables AutoFit. Default.
wdWord9TableBehavior Enables AutoFit.

Example

ShowAs it applies to the Range object.

This example converts the first three paragraphs in the active document to a table.

Set aDoc = ActiveDocument
Set myRange = aDoc.Range(Start:=aDoc.Paragraphs(1).Range.Start, _
    End:=aDoc.Paragraphs(3).Range.End)
myRange.ConvertToTable Separator:=wdSeparateByParagraphs
				

ShowAs it applies to the Selection object.

This example inserts text at the insertion point and then converts the comma-delimited text to a table with formatting.

With Selection
    .Collapse
    .InsertBefore "one, two, three"
    .InsertParagraphAfter
    .InsertAfter "one, two, three"
    .InsertParagraphAfter
End With
Set myTable = _
    Selection.ConvertToTable(Separator:=wdSeparateByCommas, _
    Format:=wdTableFormatList8)
				

  • #2

I have managed to simplify all this code and for the purposes of this query have removed a few working functions irrelevant to this query. I have also got a little bit further by finding the «Tables» operator but still stuck:

Code:

Sub CopytoWord()
Dim Wdapp As Object
    
Worksheets("Award").Range("C1:E50").Copy
     
Application.ScreenUpdating = False
    
    Set Wdapp = CreateObject("Word.Application")
    Wdapp.Documents.Add
      With Wdapp.ActiveDocument
           .Range.Paste
      End With
    Wdapp.Visible = True
  
' All the above works, below is the problem
    
      With Wdapp.ActiveDocument.Tables
          Table.Rows.ConvertToText Separator:=wdSeparateByTabs
      End With
      
End Sub

My problem is that I get a 424 «Object Required» Error. I have set Wdapp to be an object and added it in front of «ActiveDocument» so really not sure where I have gone wrong?

  • #4

Thanks very much Trevor, that is a very interesting link and I got it working no problems from Word. There are indeed loads of posts on how to convert Table to Text in VBA but these all work from within Word. I could not find one which would help me do it from Excel despite a lot of searching — perhaps I have missed them?

Based on the linked script above, I have tried to create a Word bookmark in Excel. Again there are plenty of posts on how to do this but I could find one that simply selects «all» and bookmarks it? I have therefore tried the following based on my searches and got stuck:

Code:

Dim BMRange As Word.Range

Set BMRange = Wdapp.ActiveDocument.Selection.WholeStory

Wdapp.ActiveDocument.Bookmarks.Add Range:=BMRange, name:="bmTable"

What ever permutation I try, I get stuck on line 2. I also tried Set BMRange = Wdapp.ActiveDocument.Range instead which is perhaps better. Any ideas?

  • #5

Sorry in late reply I had to go out for a while.

What I have done is created a spreadsheet with data in the same range as you mention, then I have gone into the VBA screen went to the tools menu and References and set the references to work with Microsoft Word 13.Object Library. I have then set about looking to replicate your code. Now because I am using Office 2007 in word it wasn’t possible to highlight the normal way so I have used the keyboard. I have ended up with the following code which works each time from Excel into Word, Create a new document then paste the table in then highlight and convert table to text. Please change sheet name.

I hope this will help you.

Sub wrd1()
Dim wrdApp As Word.Application
Set wrdApp = CreateObject(«Word.Application»)
Worksheets(«Sheet1«).Select
Range(«C1:E50»).Copy

With wrdApp
.Documents.Add
.Selection.Paste
.Visible = True
.Selection.HomeKey Unit:=wdStory
.Selection.MoveRight Unit:=wdCharacter, Count:=8, Extend:=wdExtend
.Selection.MoveDown Unit:=wdLine, Count:=51, Extend:=wdExtend
.Selection.MoveUp Unit:=wdLine, Count:=1, Extend:=wdExtend
.Selection.Rows.ConvertToText Separator:=wdSeparateByTabs, NestedTables:= _
True
End With
End Sub

  • #6

Trevor, that is fantastic — thank you so much for solving my problem! As usual the final solution looks so easy but was so elusive!

I have expanded on your script and after a short fight with Tabstops, I got a funny error cropping up, here is the added code:

Code:

.Selection.ParagraphFormat.TabStops.ClearAll
.Selection.ParagraphFormat.TabStops.Add Position:=CentimetersToPoints(0.75) _
        , Alignment:=wdAlignTabLeft, Leader:=wdTabLeaderSpaces

Now the funny thing is that this code works intermittently with the following Error:

462 The remote server machine does not exist or is unavailable

Basically it reliably cycles between working once and failing once and the error points at the second line. MS Word being open or closed before running the whole script makes no difference. The error is linked to commanding Word externally and following quite a bit of googling, I tried adding «wrdApp.» before Selection.Paragraph…. but this makes no difference.

I know I’ve taken enough of your time already but I don’t suppose you have any idea what could be causing this?

  • #7

Hi Trevor

I have tightened the script from my previous post using «With» where possible and this seems somehow to have eliminated this error :)

May I ask you one (hopefully) last question, as part of my formatting, I would like to select a specific section of text between two keywords. This section can change in length so using fixed line ranges will not work. I have therefore found the following code which works perfectly within Word. My problem again is applying it from VBA within Excel.

Firstly the code working within Word:

Sub SelectRangeBetween()

‘ Types the text
Selection.HomeKey Unit:=wdStory
Selection.TypeText Text:=»Hello and Goodbye»

‘ The Real script
Dim myrange As Range
Selection.HomeKey wdStory
Selection.Find.ClearFormatting
With Selection.Find
.Execute findText:=»Hello», Forward:=True, Wrap:=wdFindStop
Set myrange = Selection.Range
myrange.End = ActiveDocument.Range.End
myrange.Start = myrange.Start + 5
myrange.End = myrange.Start + InStr(myrange, «Goodbye») — 1
myrange.Select
End With
End Sub

And now my Excel adaptation:

Sub SelectRangeBetween()

Dim wrdApp As Word.Application
Set wrdApp = CreateObject(«Word.Application»)

With wrdApp
.Documents.Add
.Visible = True

‘ Types the text
.Selection.HomeKey Unit:=wdStory
.Selection.TypeText Text:=»Hello and Goodbye»

‘ The Real script
Dim myrange As Range
.Selection.HomeKey wdStory
.Selection.Find.ClearFormatting

With .Selection.Find
.Execute findText:=»Hello», Forward:=True, Wrap:=wdFindStop
Set myrange = Selection.Range
‘ Problem is here:
myrange.End = wrdApp.ActiveDocument.Range.End
myrange.Start = myrange.Start + 5
myrange.End = myrange.Start + InStr(myrange, «Goodbye») — 1
myrange.Select
End With

End With
End Sub

The error returned is «Argument not optional» and has me baffled once again…

  • #8

Trevor, that is fantastic — thank you so much for solving my problem! As usual the final solution looks so easy but was so elusive!

I have expanded on your script and after a short fight with Tabstops, I got a funny error cropping up, here is the added code:

Code:

.Selection.ParagraphFormat.TabStops.ClearAll
.Selection.ParagraphFormat.TabStops.Add Position:=CentimetersToPoints(0.75) _
        , Alignment:=wdAlignTabLeft, Leader:=wdTabLeaderSpaces

Now the funny thing is that this code works intermittently with the following Error:

462 The remote server machine does not exist or is unavailable

Basically it reliably cycles between working once and failing once and the error points at the second line. MS Word being open or closed before running the whole script makes no difference. The error is linked to commanding Word externally and following quite a bit of googling, I tried adding «wrdApp.» before Selection.Paragraph…. but this makes no difference.

I know I’ve taken enough of your time already but I don’t suppose you have any idea what could be causing this?

I have just come on line,

What I would suggest is that you look to record macros in word to finish your steps and then take a look at the code in Word and copy some of the code across. Dealing with the tabs first I have done exactly as I am suggesting and here is the end result, I have added an extra with statement to deal with the tabs, its not necessary but I wanted to break it down in steps so you can see if there is an issue, once you are happy I would combine the 2 withs into 1. I have highlighted what is missing from your extra code. I will look at your next step and post back.

Sub wrd1()
Dim wrdApp As Word.Application
Set wrdApp = CreateObject(«Word.Application»)
Worksheets(«Sheet1»).Select
Range(«C1:E50»).Copy
With wrdApp
.Documents.Add
.Selection.Paste
.Visible = True
.Selection.HomeKey Unit:=wdStory
.Selection.MoveRight Unit:=wdCharacter, Count:=8, Extend:=wdExtend
.Selection.MoveDown Unit:=wdLine, Count:=51, Extend:=wdExtend
.Selection.MoveUp Unit:=wdLine, Count:=1, Extend:=wdExtend
.Selection.Rows.ConvertToText Separator:=wdSeparateByTabs, NestedTables:= _
True
End With
With wrdApp
.Selection.ParagraphFormat.TabStops.ClearAll
.ActiveDocument.DefaultTabStop = CentimetersToPoints(1.27)
.Selection.ParagraphFormat.TabStops.Add Position:=CentimetersToPoints(0.75) _
, Alignment:=wdAlignTabLeft, Leader:=wdTabLeaderSpaces
End With
End Sub

  • #9

Hi Trevor

I have tightened the script from my previous post using «With» where possible and this seems somehow to have eliminated this error :)

May I ask you one (hopefully) last question, as part of my formatting, I would like to select a specific section of text between two keywords. This section can change in length so using fixed line ranges will not work. I have therefore found the following code which works perfectly within Word. My problem again is applying it from VBA within Excel.

Firstly the code working within Word:

And now my Excel adaptation:

The error returned is «Argument not optional» and has me baffled once again…

Please let me know what are you trying to achieve here? This is a separate question compared to your thread about getting data from Excel into Word. Look at this link to a resources site to see if it helps you with your goals.

http://www.kayodeok.btinternet.co.uk/favorites/kbofficeword.htm

  • #10

Thanks Trevor, it is indeed a separate question but as it was linked and partially based on your code suggestion I thought I could post it here. But you are right, I will start a new question on the forum for it, my apologies and thanks again, you have saved my working week with your incredibly prompt solutions!

Dear Experts:

I got two questions:

QUESTION 1:

I would like to convert text to a table. The text to be converted …
 … starts from paragraph 2 and ends at the very end of the document.
 … The separator is to be ‘COMMAS’.

I am using below code. It works fine but I’d rather use a range object instead of the selection object.

QUESTION 2:
The macro «InsertOneRowAboveTheFirstOne» inserts a row above the first one. I would like to enter text in each cell of the newly created table row. How is this achieved using VBA?

Help is much appreciated. Thank you very much in advance.

I have attached a sample file for your convenience.

Regards, Andreas  

SAMPLE-FILE-TABLE-MACRO.docx

Sub ConvertToTableSeparatedByCommas

Selection.HomeKey Unit:=wdStory
Selection.MoveDown Unit:=wdParagraph
Selection.EndKey Unit:=wdStory, Extend:=wdExtend

    WordBasic.TextToTable NumColumns:=3

End Sub


Sub InsertOneRowAboveTheFirstOne
Dim tbl as table
Dim rng as range
Dim rows as rows
Set tbl = ActiveDocument.Tables(1)
   Set rng = tbl.rows(1).Range
   Set rows = rng.rows
   rows.Select
   Selection.InsertRowsAbove 1
End Sub

Open in new window

In this article, we are delighted to offer you the way to convert Excel worksheet to native Word table via VBA.

Office files take in various formats. Now and then, you will run into the demand to convert file format from one to another. For example, conversion between Excel file and Word document is one of the most required. Actually, we’ve discussed this topic on one of our previous articles: 5 Easy Ways to Transfer Excel Tabular Data into Your Word

Today, there is a much quicker macro-way to extract Excel workbook to a Word document. And all contents in a worksheet will be converted to a native Word table.Convert Excel Worksheet to Native Word Table

Install and Run Word Macro

We will run macro in Word. Since a part of codes in the macro involves triggering Excel object, you have to add an object library reference.

  1. First and foremost, open a new blank Word document.
  2. And press “Alt+ F11” to open VBA editor in Word.
  3. Then click “Normal” on the left column.
  4. Next click “Insert” and choose “Module”.Click "Normal"->Click "Insert"->Click "Module"
  5. Now you have got a new module. Double click on it as to open.
  6. Then click “Tools” tab on the menu bar.
  7. Choose “References” on the drop-down menu.Click "Tools"->Choose "References"
  8. In the “References-Normal” window, check “Microsoft Excel 14.0 Object Library” box and click “OK”.Check "Microsoft Excel 14.0 Object Library" Box->Click "OK"
  9. Next copy and paste following codes into the new module:
Sub ExtractWorksheetsToWordDocument()
  Dim objExcel As Excel.Application
  Dim objWorkbook As Excel.Workbook
  Dim objWorksheet As Excel.Worksheet
  Dim objTable As Table
  Dim dlgFile As FileDialog
  Dim strFileName As String
 
  Application.ScreenUpdating = False
 
  ' Select an Excel file from Browse window.
  Set dlgFile = Application.FileDialog(msoFileDialogFilePicker)
 
  With dlgFile
    If .Show = -1 Then
      strFileName = .SelectedItems(1)
    Else
      MsgBox "No file is selected! Please select the target file."
      Exit Sub
    End If
  End With
 
  Set objExcel = CreateObject("Excel.Application")
  Set objWorkbook = objExcel.Workbooks.Open(strFileName)
  objExcel.Visible = False
 
  ' Step through each worksheet in the Excel file and extract data to each _
  individual section in Word document.
  For Each objWorksheet In ActiveWorkbook.Worksheets
    objWorksheet.UsedRange.Copy
    ActiveDocument.Paragraphs(ActiveDocument.Paragraphs.Count).Range.Paste
    ActiveDocument.Range.InsertAfter objWorksheet.Name
    If Not objWorksheet.Name = Worksheets(Worksheets.Count).Name Then
      With ActiveDocument.Paragraphs(ActiveDocument.Paragraphs.Count).Range
        .Collapse Direction:=wdCollapseEnd
        .InsertBreak Type:=wdSectionBreakNextPage
      End With
    End If
  Next objWorksheet
 
  For Each objTable In ActiveDocument.Tables
    objTable.Borders.Enable = True
  Next objTable
 
  ' Close the Excel application using the Quit method.
  objExcel.Application.Quit
  ' Release the object variables.
  Set objWorksheet = Nothing
  Set objWorkbook = Nothing
  Set objExcel = Nothing

  Application.ScreenUpdating = True
End Sub
  1. Click “Run” or hit “F5”.Paste Codes->Click "Run"
  2. Now there is the “Browse” window. Just select an Excel file and click “OK”.

Here is the outcome:Effect of Converting Excel Worksheet to Native Word Table

Make Sure Your Documents Still Works

There are possibly hundreds of documents stored on your computer. As time goes by, it’s easily to forget some of them. And when you remember checking them at some point, you only find them inaccessible. Then you should immediately resort to a tool to repair doc.

Author Introduction:

Vera Chen is a data recovery expert in DataNumen, Inc., which is the world leader in data recovery technologies, including fix xlsx and pdf repair software products. For more information visit www.datanumen.com

title ms.prod ms.assetid ms.date ms.localizationpriority

Working with tables

word

cf0858b7-6b39-4c90-552e-edb695b5cda3

06/08/2019

medium

This topic includes Visual Basic examples related to the tasks identified in the following sections.

Creating a table, inserting text, and applying formatting

The following example inserts a four-column, three-row table at the beginning of the active document. The For Each…Next structure is used to step through each cell in the table. Within the For Each…Next structure, the InsertAfter method of the Range object is used to add text to the table cells (Cell 1, Cell 2, and so on).

Sub CreateNewTable() 
 Dim docActive As Document 
 Dim tblNew As Table 
 Dim celTable As Cell 
 Dim intCount As Integer 
 
 Set docActive = ActiveDocument 
 Set tblNew = docActive.Tables.Add( _ 
 Range:=docActive.Range(Start:=0, End:=0), NumRows:=3, _ 
 NumColumns:=4) 
 intCount = 1 
 
 For Each celTable In tblNew.Range.Cells 
  celTable.Range.InsertAfter "Cell " & intCount 
  intCount = intCount + 1 
 Next celTable 
 
 tblNew.AutoFormat Format:=wdTableFormatColorful2, _ 
 ApplyBorders:=True, ApplyFont:=True, ApplyColor:=True 
End Sub

Inserting text into a table cell

The following example inserts text into the first cell of the first table in the active document. The Cell method returns a single Cell object. The Range property returns a Range object. The Delete method is used to delete the existing text and the InsertAfter method inserts the «Cell 1,1» text.

Sub InsertTextInCell() 
 If ActiveDocument.Tables.Count >= 1 Then 
  With ActiveDocument.Tables(1).Cell(Row:=1, Column:=1).Range 
   .Delete 
   .InsertAfter Text:="Cell 1,1" 
  End With 
 End If 
End Sub

Returning text from a table cell without returning the end of cell marker

The following example returns and displays the contents of each cell in the first row of the first document table.

Sub ReturnTableText() 
 Dim tblOne As Table 
 Dim celTable As Cell 
 Dim rngTable As Range 
 
 Set tblOne = ActiveDocument.Tables(1) 
 For Each celTable In tblOne.Rows(1).Cells 
  Set rngTable = ActiveDocument.Range(Start:=celTable.Range.Start, _ 
  End:=celTable.Range.End - 1) 
  MsgBox rngTable.Text 
 Next celTable 
End Sub
Sub ReturnCellText() 
 Dim tblOne As Table 
 Dim celTable As Cell 
 Dim rngTable As Range 
 
 Set tblOne = ActiveDocument.Tables(1) 
 For Each celTable In tblOne.Rows(1).Cells 
  Set rngTable = celTable.Range 
  rngTable.MoveEnd Unit:=wdCharacter, Count:=-1 
  MsgBox rngTable.Text 
 Next celTable 
End Sub

Converting existing text to a table

The following example inserts tab-delimited text at the beginning of the active document and then converts the text to a table.

Sub ConvertExistingText() 
 With Documents.Add.Content 
  .InsertBefore "one" & vbTab & "two" & vbTab & "three" & vbCr 
  .ConvertToTable Separator:=Chr(9), NumRows:=1, NumColumns:=3 
 End With 
End Sub

Returning the contents of each table cell

The following example defines an array equal to the number of cells in the first document table (assuming Option Base 1). The For Each…Next structure is used to return the contents of each table cell and assign the text to the corresponding array element.

Sub ReturnCellContentsToArray() 
 Dim intCells As Integer 
 Dim celTable As Cell 
 Dim strCells() As String 
 Dim intCount As Integer 
 Dim rngText As Range 
 
 If ActiveDocument.Tables.Count >= 1 Then 
  With ActiveDocument.Tables(1).Range 
   intCells = .Cells.Count 
   ReDim strCells(intCells) 
   intCount = 1 
   For Each celTable In .Cells 
    Set rngText = celTable.Range 
    rngText.MoveEnd Unit:=wdCharacter, Count:=-1 
    strCells(intCount) = rngText 
    intCount = intCount + 1 
   Next celTable 
  End With 
 End If 
End Sub

Copying all tables in the active document into a new document

This example copies the tables from the current document into a new document.

Sub CopyTablesToNewDoc() 
 Dim docOld As Document 
 Dim rngDoc As Range 
 Dim tblDoc As Table 
 
 If ActiveDocument.Tables.Count >= 1 Then 
  Set docOld = ActiveDocument 
  Set rngDoc = Documents.Add.Range(Start:=0, End:=0) 
  For Each tblDoc In docOld.Tables 
   tblDoc.Range.Copy 
   With rngDoc 
    .Paste 
    .Collapse Direction:=wdCollapseEnd 
    .InsertParagraphAfter 
    .Collapse Direction:=wdCollapseEnd 
   End With 
  Next 
 End If 
End Sub

[!includeSupport and feedback]

Понравилась статья? Поделить с друзьями:
  • Convert to number excel много ячеек
  • Convert to letter excel
  • Convert to hex excel
  • Convert to epub from word
  • Convert to capital letters in word