donderdag 22 mei 2014

Word: Button To Add a Row at the End of the Current Table; using XML and VBA

Word has a lot of buttons to add elements to a table. But there is no button to add a row at the end of the table your cursor is in. I know very well that adding a row can be done positioning the cursus in the last cell of the last row and column and then pressing the tab key. But I wanted to create a button doing this.

First of all we need a Custom UI editor for Microsoft Office to add a piece of XML to the document. My XML script looks like this:

<customUI xmlns="">
  <ribbon startFromScratch="false">
      <tab id="CV" label="CV" keytip="CV" insertBeforeMso="TabHome">
         <group id="CVactions" label="CV actions">
           <button id="AddRow" label="Add row at end of table" imageMso="FileNew" size="large" onAction="ctlAddRule" />

I added this script to a file calles AddRow.docm. In this same file a added a VBA module called Callback. In this module I put the VBA code:

Sub ctlAddRule(control As IRibbonControl)
    Dim intCol As Integer, intRow As Integer
    If Selection.Information(wdWithInTable) = True Then
        'test to determine whether your cursor is in a table
        'Selection.Tables(1) picks the current table your cursor is in
        intCol = Selection.Tables(1).Columns.Count
        intRow = Selection.Tables(1).Rows.Count
        Selection.Tables(1).Cell(intRow, intCol).Range.Select
        'selects the lowest last cell in the table
        Selection.MoveRight Unit:=wdCell
        'adds a row to the current table
        MsgBox "You cursor is not in a table"
    End If
End Sub

And you button works perfectly!

Een reactie posten