View Single Post
 
Old 07-31-2020, 11:01 PM
gmayor's Avatar
gmayor gmayor is offline Windows 10 Office 2016
Expert
 
Join Date: Aug 2014
Posts: 4,101
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 of
Default

Based on your code example the following will add a row to Table1 in the current document. The macro should go in an ordinary module and not ThisDocument


Code:
Public Sub AddRow()
'The following code conditionally adds a new row, with content controls, to the designated table.
Dim i As Long, j As Long, Prot As Long
Dim oTable As Table
Dim CCtrl As ContentControl
Const Pwd As String = ""    'Insert password (if any) here

    Set oTable = ActiveDocument.Tables(1)

    'Solicit user input
    If MsgBox("Add new row?", vbQuestion + vbYesNo) <> vbYes Then Exit Sub
    With ActiveDocument
        ' Un-protect the document, if applicable
        Prot = .ProtectionType
        If .ProtectionType <> wdNoProtection Then
            Prot = .ProtectionType
            .Unprotect Password:=Pwd
        End If
        With oTable.Rows
            'Insert an empty paragraph after our table, then replace it with a replica of the last row
            With .Last.Range
                .Next.InsertBefore vbCr
                .Next.FormattedText = .FormattedText
            End With
            'Reset all content controls in the new last row
            For Each CCtrl In .Last.Range.ContentControls
                With CCtrl
                    If .Type = wdContentControlCheckBox Then .Checked = False
                    If .Type = wdContentControlRichText Or .Type = wdContentControlText Then .Range.Text = ""
                    If .Type = wdContentControlDropdownList Then .DropdownListEntries(1).Select
                    If .Type = wdContentControlComboBox Then .DropdownListEntries(1).Select
                    If .Type = wdContentControlDate Then .Range.Text = ""
                End With
            Next
        End With
        .Protect Type:=Prot, Password:=Pwd
    End With
    Set oTable = Nothing
    Exit Sub
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