简体   繁体   中英

How do you change the color of a shape in a MS Word document using VBA triggered in MS Access?

I'm using Access to open a word document and populate some fields in Word using data from Access. Here's that code (all working ok so far):

Private Sub cmdPopulateWord_Click()

    Dim appWord As Word.Application
    Dim doc As Word.Document
    Dim TestProspCode As String

    On Error Resume Next
    Err.Clear

    Set appWord = GetObject(, "Word.Application")

    If Err.Number <> 0 Then

        Set appWord = New Word.Application

    End If

    Set doc = appWord.Documents.Open("H:\Populate Word Document from Access.docx", , True)

    With doc

        .FormFields("wtxID").Result = Me!ID
        .FormFields("wtxFirstName").Result = Me!FirstName
        .FormFields("wtxLastName").Result = Me!LastName
        .FormFields("wtxDoB").Result = Me!DateOfBirth
        .FormFields("wtxProspCode").Result = Forms!tblWordDoc!tblProspCode_sub!ProspectusCode 
        .FormFields("wtxCourse").Result = Forms!tblWordDoc!tblProspCode_sub!Course

        .Visible = True
        .Activate

    End With

    Set doc = Nothing

    Set appWord = Nothing

    Exit Sub

errHandler:
MsgBox Err.Number & ": " & Err.Description

End Sub

I'm trying to see how I can also change the colour of shape already in the same Word document referenced in the above code.

Referring to some info here , I've tried inserting the code below straight after the with in the code above.

With doc

    .Shapes("Rounded Rectange 1").Fill.BackColor.RGB = RGB(0, 0, 0)
    .Visible = msoTrue

End With

There's no error, but the shape's colour does not change to black.

What you are possibly looking for is .ForeColor property instead of .BackColor . See the code below where I additionally show how to change a border of the shape to make it look nice.

With doc.Shapes("Rounded Rectangle 1")
    'dark grey, (0,0,0) for black
    .Fill.ForeColor.RGB = RGB(80, 80, 80)
    'black borders
    .Line.ForeColor.RGB = RGB(0, 0, 0)
End With

根据 Remou 使用 MS_Word 宏记录器的提示,我发现需要引用矩形形状及其背景颜色如下:

.Shapes.Range(Array("Rounded Rectangle 1")).Fill.ForeColor.RGB = RGB(0, 0, 0)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM