目标
我正在通过 VBA 将数据从我们的 Access 数据库发布到 Word。一些正在发布的内容是富文本格式,其中一些是使用 HTML 动态格式化的,我正在使用 .InsertFile
和一个临时 HTML 文件来完成此操作。这有效,我可以将数据插入到 Word 中的表格中,但是模板中使用的所有格式都会被忽略。我已经修复了字体大小和系列,但我还要求前后的空格为特定大小,并删除多余的行。
问题
我无法更改使用 .InsertFile
发布的内容之前或之后的空格并且插入内容后始终有一个尾随空行。
示例
这是内容发布后通常的样子。
注意尾随空格以及列表如何紧靠单元格边框。
这是使用 HTML 即时生成的内容示例。
<html>
<ul>
<li>Lorem ipsum dolor sit amet</li>
<li>Lorem ipsum dolor sit amet</li>
<li>etc...</li>
</ul>
</html>
这是内容发布到模板之前的样子。
代码
魔法发生的地方,或者更确切地说,没有发生的地方。 htmlToRich
函数检查空值,删除 Unicode 字符并将字符串包装在 <html></html>
中保存到临时文件之前的标签
With oWord.selection
.Collapse Direction:=wdCollapseEnd
.Move Unit:=wdCharacter, Count:=-1
' Using htmlToRich function, format the string then wrap in
' HTML tags
.InsertFile _
filename:=htmlToRich("<ul>" & sReference & "</ul>")
' Format, unsuccessfully...
.ParagraphFormat.SpaceBefore = 6
.ParagraphFormat.SpaceAfter = 6
.Font.Size = 10
End With
最后一句话
我使用 VBA 已经大约一年了,但格式化 Word 一直被证明是我的弱点。如果您需要更多信息来帮助解决此问题,请告诉我。
编辑
在插入 HTML 后,我又尝试删除了多余的行,并成功实现了这一点。
With oWord.selection
' Using htmlToRich function, format the string then wrap in
' HTML tags
.InsertFile _
filename:=htmlToRich("<ul>" & sReference & "</ul>")
' Move the cursor to the end of the cell
.move wdCharacter
' move the cursor back two characters
.MoveEnd count:=-2
' Select the last two cell characters, which should always be a
' line break and a blank cell character.
.MoveEnd
' delete selected
.Range.Delete
End With
到目前为止,这在我的所有测试中都运行良好,即使它并不优雅。这只会给我留下一个前后空格的问题,我似乎无法使用相同的方法来解决这个问题。我能够选择列表的第一行并应用 oWord.Selection.ParagraphFormat.SpaceBefore = 6
并且没有做任何改变。回到绘图板...
最佳答案
解决尾随换行符后不久,我找到了解决前后空格问题的解决方案。
我创建了一个公共(public)子项目,允许我设置文档表格单元格的格式(我的所有内容都将发布到表格中)。我很可能会很快更新它,以删除所有尾随和前导换行符,因为它们可能会导致难看的问题。
Public Sub formatRichText(oWord As Word.Application, oDoc As Word.Document, iTable As Integer, _
iRow As Integer, iCol As Integer)
oDoc.Tables(iTable).Cell(iRow, iCol).Select
' Delete trailing paragraph character
With oWord.selection
.Move wdCharacter
.MoveEnd wdCharacter, -2
.MoveEnd
.Delete
End With
oDoc.Tables(iTable).Cell(iRow, iCol).Select
' Fix space before
With oWord.selection
.Move Count:=-1
.MoveEnd wdLine
.ParagraphFormat.SpaceBeforeAuto = False
.ParagraphFormat.SpaceBefore = 6
End With
oDoc.Tables(iTable).Cell(iRow, iCol).Select
' fix space after
With oWord.selection
.Move Count:=1
.MoveEnd Count:=-1
.ParagraphFormat.SpaceAfterAuto = False
.ParagraphFormat.SpaceAfter = 6
End With
oDoc.Tables(iTable).Cell(iRow, iCol).Select
' Format font face and size
With oWord.selection
.Font.Name = "Arial"
.Font.Size = 10
End With
End Sub
我会将之前/之后的空格应用于整个选择,但是当应用于列表时,各个项目的间距都会调整。
关于html - 通过VBA访问富文本到Word : Formatting Ignored and Added Linebreak,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29101735/