访问VBA - 重复Word表

时间:2015-02-25 14:36:41

标签: vba ms-word access-vba

我正在开发一个访问应用程序。 在应用程序结束时,我需要使用Access表中的数据填充单词模板。

我的单词模板有一个表格,表格中将填充一行。

问题是我每行需要一张桌子。所以我需要复制我的单词模板的唯一表格。

如何复制表并将其粘贴到?

这里我的当前代码可以填充第一个表

   Dim appWord As Word.Application
Dim appWord2 As Word.Application
Dim doc As Word.Document
Dim template As Word.Document
Dim db As DAO.Database
Dim rs As DAO.Recordset


On Error Resume Next

Err.Clear

Set appWord = CreateObject("Word.Application")
If Err.Number <> 0 Then

    'If Word isn't open, create a new instance of Word.

    Set appWord = New Word.Application
End If

Set appWord2 = CreateObject("Word.Application")
If Err.Number <> 0 Then

    'If Word isn't open, create a new instance of Word.

    Set appWord2 = New Word.Application
End If


Set db = CurrentDb()

'The final selected Building Blocks are in the table ConsultingOffer
Set rs = db.OpenRecordset("ConsultingOffer")

'Open the Word template
Set template = appWord.Documents.Open("C:\WordForms\Template.docx", , True)

'Open a new Word document which is a copy of the template
Set doc = appWord2.Documents.Add(template.FullName)


Dim iTable As Integer
iTable = 2

'Loop on all records to populate the word
Do While Not rs.EOF

    With doc

        .SelectContentControlsByTitle("Title").Item(1).Range.Text = rs.Fields("ModuleName")

        .Tables(iTable).Cell(1, 2).Range.Text = rs.Fields("Comments")

        .Tables(iTable).Cell(2, 3).Range.Text = rs.Fields("DeliverablesDescription")

        .Tables(iTable).Cell(5, 2).Range.Text = rs.Fields("EffortRequired") & " man-days"

        rs.MoveNext

    End With

Loop

'Save our final document as "Proposal" + date
doc.SaveAs2 ("C:\WordForms\Proposal_" & Format(Now(), "ddmmmyyyy_h\hmm_ss") & ".docx")

'Open Word Application with our final document
appWord2.Visible = True

'Quit the word template
appWord.Quit True

Set template = Nothing
Set doc = Nothing
Set appWord = Nothing
Set appWord2 = Nothing

2 个答案:

答案 0 :(得分:0)

实际上,我认为不可能复制/粘贴表格。 有人说我可能更容易用HTML创建一个新表并将其添加到第一个表中。

Source = "<table style=""display:inline;border-collapse:collapse;font-size:1em;width:100%"" border=""1""><tbody>"

        First line of the table (ID and Title)
        Source = Source & "<tr><td style=""vertical-align:top"" class=""ms-rtetablecells""><div>(Story ID) - Title:</div></td>"
        Source = Source & "<td style=""vertical-align:top"" class=""ms-rtetablecells"" colspan=2><div>" & "testing cell" & "</div></td></tr>"
        Source = Source & "</tbody></table>"

所以现在我有了我的桌子(仍然需要填写它,但没关系)。

但我还是有问题。如何将其粘贴到模板表下?

答案 1 :(得分:0)

我找到的唯一解决方案是在html上创建一个新表,然后在TextFile中写这个表,最后在我的单词模板中复制这个文件。