View Single Post
 
Old 08-12-2019, 12:32 AM
gmayor's Avatar
gmayor gmayor is offline Windows 10 Office 2016
Expert
 
Join Date: Aug 2014
Posts: 4,144
gmayor has much to be proud ofgmayor has much to be proud ofgmayor has much to be proud ofgmayor has much to be proud ofgmayor has much to be proud ofgmayor has much to be proud ofgmayor has much to be proud ofgmayor has much to be proud ofgmayor has much to be proud of
Default

As I explained, if you write to the document range you replace anything in the document range, which is what your blue text does and results in an empty one page document.

objrange is a range. It is set just above the red section, so objRange.Range.Text = txtword is incorrect. It should be objRange.Text = txtword which is what the code shows.

I assume there is nothing on page 2, so you can set the range to the document then collapse the range to its end, rather than the start, and that will write to the empty page 2 which is at the end of the document.

The macro below does not need any alteration to run from CommandButton1

Code:
Private Sub CommandButton1_Click()
Dim txtword As String
Dim objDoc As Document
Dim objRange As Range
Dim objTable As Table
Dim intRows As Integer
Dim intCols As Integer

    intRows = 8: intCols = 5
    txtword = "fsdhfkhfkdhfdskfhd fkdshfdkfhdskfhdsfd fdshgfdjdsjfg" & vbCr
    Set objDoc = Documents.Add(Template:=ThisDocument.FullName)
    Set objRange = objDoc.Range    'set the range to the document
    With objRange
        .Collapse Direction:=wdCollapseEnd    'collapse the range
        .Text = txtword    'write to the range
        .Font.Name = "Tahoma"    'format the range
        .Font.Size = "12"
        .ParagraphFormat.SpaceAfter = 0
        .Collapse Direction:=wdCollapseEnd    'collapse the range
    End With
    'add a table
    Set objTable = objDoc.Tables.Add(objRange, intRows, intCols)
    'Format the table here
    objTable.Borders.Enable = True
    objTable.Select    'select the table
    Selection.Collapse Direction:=wdCollapseEnd    'collapse the selection
    'The document is displayed with the focus at the selection
    'Clean up
    Set objDoc = Nothing
    Set objRange = Nothing
    Set objTable = Nothing
End Sub
__________________
Graham Mayor - MS MVP (Word) (2002-2019)
Visit my web site for more programming tips and ready made processes www.gmayor.com
Reply With Quote