VBA Word : Difference between Font. TextColor 和 Font.ColorIndex?

标签 vba ms-word

我有一个插入文本的宏。到目前为止,它运行良好,但是......现在,对于某些文档,当它应用颜色时,我收到错误 445。 这是代码:

'Some code before that insert a first page with a different section and writes into the header
ActiveWindow.ActivePane.View.SeekView = wdSeekMainDocument
Selection.TypeParagraph

With Selection.Font
    .Name = "Calibri"
    .Size = 14
    .Bold = True
    .Italic = False
    .TextColor = RGB(68, 114, 196)
End With

With Selection.ParagraphFormat
    .Alignment = wdAlignParagraphCenter
    .SpaceAfter = 6
End With

Selection.TypeText Text:="eReference file for work order: "
ActiveDocument.Bookmarks.Add Range:=Selection.Range, Name:="workorder"

Selection.TypeParagraph

我注意到,如果我更改“Selection.Font.TextColor = RGB(68, 114, 196)”并将其替换为“Selection.Font.ColorIndex = wdDarkBlue”,它就会起作用。因此我的问题是:两者有什么区别?为什么有些文档“Textcolor”不起作用?

谢谢!

最佳答案

Font.TextColorFont.ColorIndex两者均在 MSDN 上有记录。

颜色索引

Returns or sets a WdColorIndex constant that represents the color for the specified font. Read/write.

WdColorIndex是一个定义了许多预定义常量的枚举。作为一个枚举,它的底层值是一个数值——一个Long整数。当您将其分配给 RGB 函数调用的结果时,您将给它一个 Long 整数,而不是 WdColorIndex 值 - I非常怀疑您获得的颜色是否与您设置的 RGB 值相匹配。

文本颜色

Returns a ColorFormat object that represents the color for the specified font. Read-only.

一个ColorFormat对象使您可以更好地控制如何格式化内容。它是只读的,因为它是一个对象 - 这并不意味着您不能更改它(例如修改其状态),它只意味着您不能将该对象引用设置到其他对象...但无论如何您都不需要这样做。

所以代替这个:

.TextColor = RGB(68, 114, 196)

你可以这样做:

 .TextColor.RGB = RGB(68, 114, 196)

ColorFormat.RGB Property on MSDN .

FWIW 当尝试将非 WdColorIndex 枚举值分配给 Font.ColorIndex 时,我收到运行时错误 5843,所以我对您的内容感到困惑意思是“它有效” - 尤其考虑到IntelliSense为您提供了它的可能值:

wdColorIndex constants

关于VBA Word : Difference between Font. TextColor 和 Font.ColorIndex?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42488755/

相关文章:

php - 在 PHP 中读取 docx(Office Open XML)

java - 如何使用 OLE 自动化关闭 Word 文档?

c# - 使用 C#/Java/Visual Basic 填充 Word 2007 模板

excel - VBA,EXCEL,字: Formatting of Horizontal line from Excel in Word Header

sql - 无论如何将SQL查询提取到Excel中

excel - 当我不知道上限值时如何在excel vba中使用 'ReDim Preserve'

c# - 使用 NPOI 将图像添加到 Word docx 文件

mysql - Excel Vba 从 mysql 数据库中删除行时出现问题

vba - 使用 Excel VBA 导出后命名 PDF

c# - C# 中的 Word 自动化语法