-1

I am working adding a field to a document and adding shading. The following code is not working.

With Selection
    .Range.Font.Shading.BackgroundPatternColor = wdColorLightYellow
    .Fields.Add Range:=Selection.Range, Type:=wdFieldEmpty, _
        PreserveFormatting:=False, Text:="Page"
    .Fields.Update
End With
'ActiveDocument.Fields(1).Select
'Selection.Range.Font.Shading.BackgroundPatternColor = wdColorLightYellow

The commented-out lines will add the shading to the first field in the document.

braX
  • 11,506
  • 5
  • 20
  • 33
Charles Kenyon
  • 869
  • 1
  • 8
  • 19

2 Answers2

0

At the point you apply the shading there is nothing selected, the start and end points of the range are the same. Although in the UI you can apply formatting such as bold or italic before typing, applying shading would apply it to the entire paragraph.

To just shade the field it needs to be selected before applying the shading, as it is in the alternative code in your question.

With Selection
    .Fields.add Range:=Selection.Range, Type:=wdFieldEmpty, _
        PreserveFormatting:=False, text:="Page"
    .Fields.Update
    .MoveLeft Extend:=wdExtend
    .Range.Font.Shading.BackgroundPatternColor = wdColorLightYellow
    'this also works
    '.Shading.BackgroundPatternColor = wdColorLightYellow
End With
Timothy Rylatt
  • 7,221
  • 2
  • 10
  • 14
0

Since you are using VBA there is something to be said for using "With" to work with the field object that you just created, e.g.

With Selection
  With .Fields.Add( _
    Range:=Selection.Range, _
    Type:=wdFieldEmpty, _
    PreserveFormatting:=False, _
    Text:="Page")
    .Update
    ' you either need to color .Code, .Result, or both  
    .Code.Font.Shading.BackgroundPatternColor = wdColorLightYellow
    .Result.Font.Shading.BackgroundPatternColor = wdColorLightYellow
  End With
End With