【问题标题】:Setting font size in Word via VBS only works on some documents通过 VBA 在 Word 中设置字体大小仅适用于某些文档
【发布时间】:2015-08-07 02:53:51
【问题描述】:

我正在尝试通过 VBScript 以编程方式修改一组 Word 标题。

我采取的步骤如下(在伪代码中):

For each word-document in source-folder
    Open word-document
    Clear current headers 
    Clear current tabstops
    Set font to 9
    Insert prepared string
    Close word-document
End For

我遇到的问题是一小部分但一致的文档组已应用了所有步骤除了字体更改。

我用来执行字体更改的代码如下:

Sub setFont
    ' Select the header view
    WordApp.ActiveWindow.ActivePane.View.SeekView = 9 
    ' Set the font to 9
    WordApp.ActiveWindow.Selection.Font.Size = "9"
    ' Go back the the main body view
    WordApp.ActiveWindow.ActivePane.View.SeekView = 0 
End Sub

据我所知,脚本失败的那批文档没有任何独特之处。该文档集包含各种字体大小和制表位位置,并且该脚本适用于该集中的 70 多个其他文档。

如果有人可以帮助我确定为什么该代码无法在某些文档上运行,我将非常感激。

【问题讨论】:

  • 您可以手动更改其中一个文档的字体大小吗?使用宏记录器记录手动更改其中一个问题文件中的字体,看看是否显示任何内容。
  • @ChipsLetten 这样做会产生以下 VBA:'Selection.WholeStory Selection.Font.Size = 9' 你有什么建议如何将它集成到我的 Sub 中吗?我承认在从 VBA 迁移到 VBS 时我有点迷茫。 (编辑:发布得太早了。)

标签: vba vbscript ms-word formatting ms-office


【解决方案1】:

您可能需要设置Selection 以便它包含整个标题。这是添加了代码行的代码。警告:未经测试!

Sub setFont()
    ' Select the header view
    WordApp.ActiveWindow.ActivePane.View.SeekView = 9
    ' Make the selection the entire header
    WordApp.ActiveWindow.Selection.WholeStory
    ' Set the font to 9
    WordApp.ActiveWindow.Selection.Font.Size = "9"
    ' Go back the the main body view
    WordApp.ActiveWindow.ActivePane.View.SeekView = 0
End Sub

您可能可以在此代码中使用With ... End With 块:

Sub setFont()
    With WordApp.ActiveWindow
        ' Select the header view
        .ActivePane.View.SeekView = 9
        ' Make the selection the entire header
        .Selection.WholeStory
        ' Set the font to 9
        .Selection.Font.Size = "9"
        ' Go back the the main body view
        .ActivePane.View.SeekView = 0
    End With
End Sub

【讨论】:

  • 按照您的建议修改的脚本运行没有错误,但仍然没有更改问题文档上的字体。 (感谢您的 With...End With 示例。这是一个有用的符号!)编辑:我可以提供有关问题文档的更多信息吗?
  • 如果在 VBA 中运行代码,字体大小会改变吗?不知道我还能建议什么。您可以在某处发布示例问题文档吗?
  • 确实如此。这是拒绝改变的其中之一:dropbox.com/s/zrqvp6rs15aj18b/Sample.doc?dl=0
  • 该文档的标题中没有任何内容。有关选择语言的文本和可用选项位于文档的正文中。
  • 我的浏览器没有得到正确的文件。现在更有意义了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多