文档打开时设置字体颜色不起作用

时间:2013-11-07 16:49:07

标签: vba word-vba word-2007

所以我正在为一些人创建一个文档,其中每个组(其中有三个组)被分配了一种字体颜色,用于输入文档。我编写了一个VBA脚本,其中包含所涉及的每个人的列表,可以识别登录到计算机的人员以及他们所在的组。但是,我无法获得字体颜色来设置自己。我录制了一个VBA脚本,我在其中设置字体颜色以查看Word是如何做到的,但是当我将其添加到我的VBA脚本时,生成的Selection.Font.Color = wdColorRed代码实际上不会更改所选的字体颜色。以下是我正在使用的代码示例:

Private Sub Document_Open()

Dim Users As New Scripting.Dictionary
Dim UserID As String
Dim category As String

UserID = GetUserName 'Currently using the example at
                     'http://support.microsoft.com/kb/161394 as a function

'---Add Members of Group 1---
Users.Add "person1", "group1"
Users.Add "person2", "group1"

'---Add Members of Group 2---
Users.Add "person3", "group2"
Users.Add "person4", "group2"
Users.Add "person5", "group2"

'---Add Members of Group 3---
Users.Add "person6", "group3"
Users.Add "person7", "group3"

For Each user In Users.Keys
    If user = UserID Then
        If Users.Item(user) = "group1" Then
            Selection.Font.Color = wdColorRed
        ElseIf Users.Item(user) = "group2" Then
            Selection.Font.Color = wdColorGreen
        ElseIf Users.Item(user) = "group3" Then
            Selection.Font.Color = wdColorBlue
        Else
            Selection.Font.Color = wdColorBlack
        End If
    End If
Next

End Sub

2 个答案:

答案 0 :(得分:0)

AFAIK,您无法为特定用户设置默认字体颜色。即使您设法将其设置为蓝色并导航到一个红色的句子,如果您键入任何内容,您将看不到蓝色文本而是红色文本。因为光标所在的位置将选择用于为该句子着色的原始颜色。

要为用户设置特定颜色,您必须

  1. Identify a range and set the color for it。但就像我上面提到的那样,如果用户导航到不同的范围,那么新的颜色设置将不适用于那里。

  2. Set it for the entire document。如果您为整个文档设置它,那么整个文档的颜色将会改变,我确信这不是您想要的。

答案 1 :(得分:0)

可能的解决方法基于Application.WindowSelectionChange Event。因此,您需要执行以下步骤:

1.创建班级模块
2.将您的班级模块命名为App
3.将以下代码添加到App Class Module

    Public WithEvents WRD As Application

    Private Sub WRD_WindowSelectionChange(ByVal Sel As Selection)
        'here you should place solution from your Document_Open sub
        'which defines color based on user name or...
        'you could place it somewhere else but pass color value 
        'here as a parameter

        'for test I just assumed that color should be blue
        Sel.Font.Color = wdColorBlue
    End Sub

4.在标准模块中添加公共变量:

    Public tmpApp As New App

5.在标准模块中创建Sub,或者将代码添加到Document_Open Event,这将初始化我们的课程:

Sub Document_Open_new()

    Set tmpApp.WRD = Application

    'we need to change selection once to trigger full
    'scope of solution
    'if we omit the code below new color will not work
    'if user add new text at the beginning of the document
    'right after it was opened
    Dim tmpSel As Range
    Set tmpSel = Selection.Range
    ActiveDocument.Bookmarks("\EndOfDoc").Select
    tmpSel.Select
End Sub

6.如果代码已添加到Document_open event,则运行上述子文件或打开文档。

---编辑--- (在@Sid的一些评论之后)

使用提出的解决方案有一些不便之处。但是,通过在If statements内添加一些WindowSelectionChange event,可以解决大部分问题。检查Sel range参数的位置,文本及其他位置可以精确地决定是否应该应用新颜色。