Thursday, September 8, 2011

Colour a form field check box with a contrasting colour when it is checked.



In the following illustration the checked form field check box is coloured red. This can be achieved by checking the value of the check box and formatting the check box when the value is 'True'. The code uses the function Private Function GetCurrentFF() As Word.FormField used in the Bar Chart example above to get the current field name, so that the same macro can be applied to the On Exit property of each check box field.



Private mstrFF As String
Sub EmphasiseCheckedBox()
Dim oFld As FormFields
Dim sCount As Long
Dim bProtected As Boolean
Dim sPassword As String

sPassword = "" 'Insert the password (if any), used to protect the form between the quotes
With GetCurrentFF 'Establish field is current
     mstrFF = GetCurrentFF.name
End With

Set oFld = ActiveDocument.FormFields
sCount = oFld(mstrFF).CheckBox.Value 'Get the Checkbox field value
'Check if the document is protected and if so unprotect it

If ActiveDocument.ProtectionType <> wdNoProtection Then
     bProtected = True
     ActiveDocument.Unprotect Password:=sPassword
End If

With oFld(mstrFF).Range
     If sCount = True Then
          .Font.Color = wdColorRed 'Set the colour of the checked box
     Else
          .Font.Color = wdColorAutomatic 'Set the colour of the unchecked box
     End If
End With

 

'Re-protect the form and apply the password (if any).
If bProtected = True Then
     ActiveDocument.Protect _
     Type:=wdAllowOnlyFormFields, NoReset:=True, Password:=sPassword
End If
End Sub


Private Function GetCurrentFF() As Word.FormField
Dim rngFF As Word.Range
Dim fldFF As Word.FormField
Set rngFF = Selection.Range
rngFF.Expand wdParagraph
For Each fldFF In rngFF.FormFields
     Set GetCurrentFF = fldFF
Exit For
Next
End Function

No comments:

Post a Comment