使用MS Access表中的数据填充MS Word表

时间:2016-02-28 13:11:21

标签: vba ms-word access-vba

我尝试将访问表中的数据填充到字表中。

在开头我有一个空表,在单词模板中有1行和2列,当它运行代码时,我最后有一个包含8行和2列的表,这很好。还有一个我在访问表中有数据集,但是确定......

但是表格中的所有字段都是空的,为什么不填充单元格:

.Tables(2).Cell(row, col).Range.Text = rs!short    

这是循环:

Set rs = DB.OpenRecordset("tbl_abbreviations", dbOpenDynaset, dbSeeChanges)
    rs.MoveFirst
    col = 1
    row = 1
    Do While Not rs.EOF
    .Tables(2).Cell(row, col).Range.Text = rs!short
    col = col + 1
    .Tables(2).Cell(row, col).Range.Text = rs!Description
    .Tables(2).Rows.Add
    col = 1
    row = row + 1

    rs.MoveNext
    Loop

甚至有点奇怪的是这会起作用:

.Shading.BackgroundPatternColorIndex = wdBlue

但这不起作用:

.Shading.BackgroundPatternColorIndex = RGB(104, 212, 248)

我忘了激活某些东西吗?

1 个答案:

答案 0 :(得分:1)

在我看来,你的方法不是最优的。逐个单元地写入Word表是低效的。

更好的做法是将数据写入分隔的字符串格式,将该字符串分配给" target" Word文档中的范围位置(通常是书签)然后将范围转换为表格,然后您可以格式化。

分隔字符串格式的示例数据内容:

Short;Description
s1;the first record
s2;the second record
s3;and so on...

用于写入书签并转换为表格的代码段:

Dim sData As String
Dim rng As word.Range
Dim tbl As word.Table

sData = "Short;Description" & vbCr & "s1;the first record" & vbCr _
        & "s2;the second record" & vbCr & "s3;and so on..."
Set rng = ActiveDocument.Bookmarks("test").Range
rng.Text = sData
Set tbl = rng.ConvertToTable(";")

替换您的代码以读取Access表并将其写入sData。您可以使用任何所需的字段分隔符,它不必是分号。但记录分隔符必须是vbCr(ANSI 13)。请务必指定您在ConvertToTable函数中使用的字段分隔符。

获得tbl对象后,您可以使用它来应用格式化。这比使用Tables(index)集合方法重复使用表格更可靠,更有效。