Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Word VBA - Create Table and Populate 1

Status
Not open for further replies.

stevio

Vendor
Jul 24, 2002
78
AU
Trying to use VBA to create a table using bookmarks in Word 2010 from a Userform with 2 columns and row based on number of checkboxes ticked. Then populate just the first column with predefined text and the row number

The second column, would contain the Caption or name of the checkbox. I don't know if this is possible

So, if the number of rows was 3, then it would create a table, like

Text 1 Text from Caption of Checkbox1
Text 2 Text from Caption of Checkbox2
Text 3 Text from Caption of Checkbox3

So far, I am stuck on the first column, code thus far

Code:
Dim Ctl As Control 'count the number of checkboxes checked
        For Each Ctl In Userform1.Controls
          If TypeOf Ctl Is MSForms.CheckBox Then
            If Ctl Then Count = Count + 1
          End If
        Next
Dim oTable As Table
Dim r As Integer
Dim c As Integer
Dim oCell As Cell
    If ActiveDocument.Bookmarks.Exists("bookmark1") = True Then
        Set myRange = ActiveDocument.Bookmarks("bookmark1").Range
        ActiveDocument.Tables.Add Range:=myRange, NumRows:=Count, NumColumns:=2
        Set oTable = ActiveDocument.Tables(1)
        Set oCell = oTable.Cell(Row:=1, Column:=1)
        oCell.Range.text = "Text " & Count
        For r = 1 To Count
            oCell.Range.text = "Text " & Count
            Count = Count + 1
        Next
       
    End If

End Sub

This code only creates the table and places "Text 1" in the first cell of the table

Any ideas would be appreciated
 
The basic problem is that you're not changing the destination, which you've set via the 'Set oCell = oTable.Cell(Row:=1, Column:=1)' reference. Try:
Code:
Dim Ctl As Control 'count the number of checkboxes checked
Dim StrBkMk As String, Rng As Range, oTable As Table, r As Long, x As Long
StrBkMk = "bookmark1"
With ActiveDocument
  If .Bookmarks.Exists(StrBkMk) = True Then
    Set Rng = .Bookmarks(StrBkMk).Range
    For Each Ctl In Userform1.Controls
      If TypeOf Ctl Is MSForms.CheckBox Then
        If Ctl = True Then x = x + 1
      End If
    Next
    Set oTable = .Tables.Add(Range:=Rng, NumRows:=x, NumColumns:=2)
    With oTable
      For r = 1 To x
        .Cell(Row:=r, Column:=1).Range.Text = "Text " & r
      Next
    End With
  End If
End With
Set oTable = Nothing: Set Rng = Nothing

Cheers
Paul Edstein
[MS MVP - Word]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top