How to use a word table as mailmerge datasource - vba

I have a word document containing a table I need to use as mailmerge datasouce.
I've reached my goal by copying data of the word table to excel and using the sheet as datasource.
Now my question is: is there a way to use the word table as datasource (I mean create a datasource using the data in the word table) without calling excel?
I'm asking this because I need to use a word-vba macro and I'm trying to avoid opening an excel instance.
edit
I'll try to clarify what I'm looking for with the following pseudocode (I added a "What for this?" in wrong code lines):
Dim mDoc As Document
Dim mTbl As Table
Set mDoc = ActiveDocument
Set mTbl = mDoc.Tables(1)
Dim mDS As MailMerge.DataSource 'What for this?
For C = 1 To mTbl.Columns.Count
'Add Fields
Dim FieldName As String
FieldName = mTbl.Cell(1, C).Range.Text
mDS.Fields.Add (FieldName) 'What for this?
'Add Values
For R = 2 To mTbl.Rows.Count
mDS.Fields(FieldName)(R) = mTbl.Cell(R, C).Range.Text 'What for this?
Next R
Next C

In Word, start with a blank document, then add one table. Enter the category in the top row (i.e. First Name, Last Name, etc). Then add the data in the rows below. Then you should be able to use a statement like this to connect:
ActiveDocument.MailMerge.OpenDataSource Name:="Y:\Test\Word\MailmergeSource.docx", LinkToSource:=True, SubType:=wdMergeSubTypeOther

Related

Userform populates wrong table in word document

I have been using google for a while and finally decided to ask here for help.
Basically I have a word documents with a couple of tables that is being used by different people. Each table has a VBA button "add new row". Click on a button and a userform is filled out. Userform populates the table. Only problem left is there are multiple tables and userforms and they populate the wrong table.
How can I populate the right tables with userforms?
Googling helped me that bookmarks are needed. I set a bookmark called
Table and Bookmark
Userform
Notation/Names
Code for clicking add in userforms:
Private Sub CommandButtonAdd_Click()
Dim table2 As table
Dim newRow As Row
Set table2 = ActiveDocument.Tables(1)
Set newRow = table2.Rows.Add
newRow.Cells(1).Range.Text = TextBoxFunction.Text
newRow.Cells(2).Range.Text = TextBoxName.Text
End Sub
First time using VBA, credits go to this person: https://www.youtube.com/watch?v=9cZ_XWzQZX0
Many many thanks for your help.
You choose the table by index. If you have any mask you can recognize the correct table, you can try to check all the tables and recognize the right one with loop
Dim tempT as Variant
Dim count as long
count=0
For Each tempT in ActiveDocument.Tables
count=count+1
if ActiveDocument.Tables(count) 'here some condition to recognize the corrct table ' Then
Set newRow = table2.Rows.Add
'etc your code
End If
Next tempT

Loop through each row in dynamic column using Excel Tables and VBA

I am trying to loop through various elements in a Vertical Excel Table and pass them to a horizontal table using VBA. The vertical table is a form that contains a list of questions (name,label,value) and the horizontal table will contain columns using the question name from the vertical table.
The code looks something like this:
Dim row As Range
Dim rowCount As Integer: rowCount = 1
For Each row In [tbl_QUESTIONS[name]].Rows
Sheets(ANSWERS).Cells(r,rowCount).Value = row.Value
rowCount = rowCount + 1
Next
My question is, how can modify the table reference and column reference so that they are dynamic?
[tbl_QUESTIONS[name]].Rows
I would like to be able to do something like this:
["tbl_" & tblName & "[" & colName & "]]".Rows
But that doesn't seem to work... Is there a simpler way to reference this using VBA? I get the feeling that there has to be a way of creating the ListObject out of ["tbl_" & tblName] but I haven't been able to reference 'colName' inside the ListObject or the ListObject.Rows
Any help would be appreciated.
Oh, and I'd like to keep this compatible with Excel 2007 VBA if at all possible.
Cheers!
I've stumbled upon this link and it seems to do the trick.
Looks like I can create a range using the following:
Dim TBL As Range
Set TBL = Range("tbl_" & tblName & "[" & colName & "]")
I'd still like to see a way of keeping the ListObject rather than defining a range, but I'll go with this until I have an alternative.
You probably know this by now but since the question has no answer...
use the LisObjects collection to select a listObject and pass that as a parameter to your function/sub

Save Word document as a filename generated from tabled info contained within the document

I am looking to enable Word to save with a file name using data contained within the document.
At the top of the document (an airline release letter), there is a table containing 2 columns with 3 rows containing alpha in one column and alpha-numeric data in column 2.
Column 1,
Cell 1: AETC; Cell 2: MAWB; Cell 3: HAWB
Column 2,
Cell 1: 80123; Cell 2, 0161234567; Cell 3: 00112345678
Basically, the first column will be the static labels for the variable data to be entered into column 2.
From all this, I want to generate a save-as file name: AETC80123_MAWB0161234567_HAWB00112345678_ReleaseLetter.doc
I've barely scratched the surface of VBA as I am more an operations supervisor than a techie so I'm not certain if this is even possible.
Any help/direction/copy-paste coding (if it's super easy and of little trouble) would be awesome!
Thanks!
I am not going to work it all out in detail for, nor is this tested at all (just written out of my head), but this should give a hint how you read cell content in a Word document:
' Set tbl to first table in document
Dim tbl As Table
Set tbl = ActiveDocument.Tables(0)
Dim r As Integer
Dim c As Integer
Dim val As String
Dim filename As String
filename = ""
For r = 1 To tbl.Rows.Count
For c = 1 To tbl.Columns.Count
' Get text in cell
val = tbl.Cell(r, c).Range.Text
' and append to string or whatever
filename = filename & val & "_"
Next c
Next r
Finally, save your document using
ActiveDocument.SaveAs FileName:=filename
Check this microsoft site for more information about SaveAs parameters.

Word 2010 template table generation

I'm trying to use Word 2010 to create a template for a programming project test plan. I've created a mockup template showing what I want to do.
What I'd like to be able to do is be able to click on something on the Word ribbon, and have the template generate the next test table and sequence the caption. Once the table is generated, I would fill in the table fields for the test.
Could someone tell me what to look up in the Word help or elsewhere so I can create this template?
I personally would create a macro for this or you can embed it in your template with code to add menu items and add something like the following. (It's very rough but you can use it to generate a table with your layout and numeric ascending numbers), it is not as dynamic as knowing where the previous test left off but should be a start point.)
Dim iCount As Integer
iCount = CInt(InputBox("How many tables?", "Table Count", 1))
For icurtable = 1 To iCount
Dim oTableRange As Paragraph
Dim oTable As Table
Dim oCaption As Paragraph
Set oCaption = ActiveDocument.Paragraphs.Add
Call oCaption.Range.InsertBefore(CStr(icurtable))
Set oTableRange = ActiveDocument.Paragraphs.Add
Set oTable = oTableRange.Range.Tables.Add(oTableRange.Range, 4, 1, True, True)
oTable.Rows.First.Cells(1).Range.InsertBefore ("Setup:")
oTable.Rows(2).Cells(1).Range.InsertBefore ("Test:")
oTable.Rows(3).Cells(1).Range.InsertBefore ("Expected Response:")
oTable.Rows(4).Cells(1).Range.InsertBefore ("Restore")
Call oTableRange.Range.InsertAfter(vbCrLf)
Next
In case someone else comes across this question, I'll provide my solution. I decided to create a table inside of a table so the test case number will be on the left, where people expect to see it.
Using Sacha's answer as a model, and making liberal use of the macro recorder, I came up with this VBA macro that does most of what I want.
Sub InsertTestTable()
'
' InsertTestTable Macro
' This macro inserts a test table into the document.
'
Dim oTable As Table
Dim iTable As Table
Set oTable = ActiveDocument.Tables.Add(Selection.Range, 1, 2, _
wdWord9TableBehavior, wdAutoFitContent)
Selection.TypeText ("1.")
Selection.MoveRight
Set iTable = ActiveDocument.Tables.Add(Selection.Range, 4, 2, _
wdWord9TableBehavior, wdAutoFitContent)
iTable.Rows(1).Cells(1).Range.InsertBefore ("Setup:")
iTable.Rows(2).Cells(1).Range.InsertBefore ("Test:")
iTable.Rows(3).Cells(1).Range.InsertBefore ("Expected Response:")
iTable.Rows(4).Cells(1).Range.InsertBefore ("Restore:")
iTable.Rows(1).Cells(2).Range.Select
End Sub
Now, all I need to do is format the tables the way I want, and figure out how to have the number ascend through the set of tables in the document.

Positioning a table at a specific location

I have written a macro to allow a user to select an office branch from a combo box, and now I want to insert the relevant address into the word document at a specific location. I have it using a table to hold the address, however when the table is created, it is created at wherever position the cursor just happens to be sitting at on the page.
I can't seem to find a way to tell the table to position exactly (x,y) where I need it to appear. Since there is nothing else in the document but text, there is nothing to reference to.
I am also trying to stay away from using Active X controls if at all possible.
This code will add a three column, one row table between the second and third paragraphs.
Sub InsertTable()
Dim tbl As Table
Dim pg As Paragraph
With ThisDocument
'Add a new paragraph that the table will replace
Set pg = .Paragraphs.Add(.Paragraphs(3).Range)
'Add a table in place of the new paragraph
Set tbl = .Tables.Add(pg.Range, 1, 3)
End With
tbl.Columns(1).Cells(1).Range.Text = "123 Main St"
tbl.Columns(2).Cells(1).Range.Text = "City"
tbl.Columns(3).Cells(1).Range.Text = "State"
tbl.Rows.LeftIndent = 41
End Sub
You may use this to position table both horizontally and vertically
tbl.Rows.HorizontalPosition = 150 'In points
tbl.Rows.VerticalPosition = 200
Hope that helped.
I had trouble grasping the code with the with-statement from Dick Kusleika's answer, so I'd like to share my version without the with-statement, for people like me much easier to understand:
Sub InsertTable()
Dim tbl As Table
Dim pg As Paragraph
'Add a new paragraph that the table will replace
Set pg = ThisDocument.Paragraphs.Add(ThisDocument.Paragraphs(3).Range)
'Add a table in place of the new paragraph
Set tbl = ThisDocument.Tables.Add(pg.Range, 1, 3)
tbl.Columns(1).Cells(1).Range.Text = "123 Main St"
tbl.Columns(2).Cells(1).Range.Text = "City"
tbl.Columns(3).Cells(1).Range.Text = "State"
tbl.Rows.LeftIndent = 41
End Sub