View Single Post
 
Old 08-11-2019, 12:19 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

There are some similarities between Word and Excel, but they are not the same when it comes to programming. If you Add a document without reference to the template, which is what you had originally, then a new document is created from the normal template. Essentially a blank document unrelated to your document with the button. If you want to create a new document that has the button then you need to refer to the template e.g.

Set objDoc = Documents.Add(Template:="C:\WordTrial\cmdBtnWord.d ocm")

This will create a new document that is an unnamed facsimile of the original. Or as it is a macro enabled document, you can simply open it as in your subsequent attempt.

Having got the document open/created your code then writes a text value to the document range, which overwrites everything in the document body. You need instead to set a range to the start (or end) of the document and write to that e.g.

Code:
Dim txtword As String
Dim objDoc As Document
Dim objRange As Range
Dim objTable As Table
Dim intRows As Integer
Dim intCols As Integer
    txtword = "fsdhfkhfkdhfdskfhd fkdshfdkfhdskfhdsfd fdshgfdjdsjfg" & vbCr
    Set objDoc = Documents.Add(Template:=ThisDocument.FullName)
    Set objRange = objDoc.Range
    objRange.Collapse Direction:=wdCollapseStart
    objRange.Text = txtword
    objRange.Collapse Direction:=wdCollapseEnd
    intRows = 8: intCols = 5
    Set objTable = objDoc.Tables.Add(objRange, intRows, intCols)
    objTable.Borders.Enable = True
AutoNew and AutoOpen are built-in macro names that run when the document is opened or created and go in a standard module. They perform similar roles to Document_New and Document_Open

You would need to modify the ribbon in order to add a button there. See Customize the Office Ribbon (It doesn't take rocket science)
__________________
Graham Mayor - MS MVP (Word) (2002-2019)
Visit my web site for more programming tips and ready made processes www.gmayor.com

Last edited by gmayor; 08-12-2019 at 12:12 AM.
Reply With Quote