您可以使用 ContentControl 的 Exit 事件。当用户移出单元格时,它会根据所选内容进行格式化。此代码位于 ThisDocument 模块中。
Private Sub Document_ContentControlOnExit(ByVal ContentControl As ContentControl, Cancel As Boolean)
Select Case ContentControl.Range.Text
Case "Yes"
ContentControl.Range.Cells(1).Shading.BackgroundPatternColorIndex = wdGreen
Case "No"
ContentControl.Range.Cells(1).Shading.BackgroundPatternColorIndex = wdRed
Case "Unknown"
ContentControl.Range.Cells(1).Shading.BackgroundPatternColorIndex = wdYellow
Case "Not Applicable"
ContentControl.Range.Cells(1).Shading.BackgroundPatternColorIndex = wdGray50
End Select
End Sub
如果您使用旧式下拉菜单作为表单字段,则可以将此子项设置为退出宏。您必须完成所有选项的宏。
Public Sub LegacyDropDownExit()
ThisDocument.Unprotect
Select Case Selection.FormFields(1).Result
Case "Yes"
Selection.Cells(1).Range.Shading.BackgroundPatternColorIndex = wdGreen
Case "No"
Selection.Cells(1).Range.Shading.BackgroundPatternColorIndex = wdRed
End Select
ThisDocument.Protect wdAllowOnlyFormFields, True
End Sub
如果你使用 ActiveX 控件,你可以这样做
Private Sub ComboBox1_Change()
ChangeCellBg Me.ComboBox1.Value, 1
End Sub
Private Sub ComboBox2_Change()
ChangeCellBg Me.ComboBox2.Value, 2
End Sub
Private Sub ComboBox3_Change()
ChangeCellBg Me.ComboBox3.Value, 3
End Sub
Private Sub ChangeCellBg(ByVal sValue As String, ByVal lRow As Long)
Select Case sValue
Case "Yes"
Me.Tables(1).Cell(lRow, 2).Range.Shading.BackgroundPatternColorIndex = wdGreen
Case "No"
Me.Tables(1).Cell(lRow, 2).Range.Shading.BackgroundPatternColorIndex = wdRed
End Select
End Sub
您还可以创建一个类模块,这样您就不必创建所有这些更改事件,但这超出了此答案的范围。