PDA

View Full Version : Solved: Create multiple tables from list items



airways6
12-02-2011, 09:39 AM
Hello, I'm trying to do the following in word with VBA. I have e listbox filled with items. For each item, a table 1 cell has to be created. I got it working with adding rows to an existing table. but when i try to create the tables directly in VBA all the list items are put in on cell instead of one table per item.

this is what i have. Can some help me with the code to create multiple tables instead of rows? Thanks!



Private Sub cmdOk_Click()


'Dim i As Integer
'Dim j As Integer

'i = ActiveDocument.Tables(3).Rows.Count - 1
'With ActiveDocument.Tables(3)
' For j = 0 To lstAdd.ListCount - 1
' .Rows.Add
' .Cell(j + 1, 1).Range.Text = lstAdd.List(j, 0)
' Next
'End With

Unload Me


End Sub

Tinbendr
12-03-2011, 02:18 PM
Private Sub cmdOk_Click()
Dim j As Integer

With ActiveDocument.Tables(3)
For j = 0 To lstAdd.ListCount - 1
.Rows.Add
.Cell(.Rows.Count, 1).Range.Text = lstAdd.List(j, 0)
Next
End With

Unload Me
End Sub

airways6
12-04-2011, 03:47 AM
Thanks David,

But this still creates rows instead of separate tables. I've been strubbeling yesterday and i've added some code that seems to do the job. However this creates the tables above the first one, and it need to be below. In other words The first list Item ends up at the end of the document and the last list item is at the top of the document. I can not change the list, because it need to be alphabetical (a-z). What is the code the be sure that the tables are created with a insertbreak below each other?

Many thanks...

Private Sub cmdOk_Click()

Dim j As Integer
Dim oRng As Word.Range
Dim objTable As Word.Table
Set oRng = ActiveDocument.Bookmarks("bmtabel").Range
For j = 0 To lstAdd.ListCount - 1
Set objTable = ActiveDocument.Tables.Add(Range:=oRng, NumRows:=1, NumColumns:=1)
With objTable
.Cell(j + 1, 1).Range.Text = lstAdd.List(j, 0)
.Rows.Add
.Borders.OutsideLineStyle = wdLineStyleSingle
.Borders.OutsideLineWidth = wdLineWidth025pt
.Borders.InsideLineStyle = wdLineStyleSingle
.PreferredWidthType = wdPreferredWidthPercent
.PreferredWidth = 100
.Range.InsertBreak Type:=wdColumnBreak
End With
Next

Unload Me

End Sub

Tinbendr
12-04-2011, 05:45 AM
But this still creates rows instead of separate tables. Sorry. I misunderstood.

Just count backwards.

For j = lstAdd.ListCount - 1 To 0 Step -1

airways6
12-07-2011, 10:46 AM
Thanks david,
That was what i was looking for...
This works fine