如何在Microsoft Word中将条件格式添加到我现有的VB代码中?

时间:2019-05-16 08:41:20

标签: vba ms-word

我在MS Word中有一个表,该表包括下拉列表项以及根据所选下拉列表项的组合显示和输出值的列。我试图使结果单元格根据其内容填充颜色。例如。任何以> = 70开头的颜色都将变为红色。

我该怎么做?

我知道这应该在Excel中完成,但不幸的是,我必须处理已有的东西。

我尝试使用宏并确实改变了颜色,但是我现有的VB代码(下面列出,然后停止工作)。

Private Sub Document_ContentControlOnExit(ByVal CC As ContentControl, Cancel As Boolean)
Dim CField As String, LField As String, RField As String, CText As String, LText As String, CRate As Double, LRate As Double, RRate As Double, RCat As String, RCatField As String
Select Case CC.Title
Case "C1", "L1"
CField = "C1"
LField = "L1"
RField = "R1"
RCatField = "RR1"

Case "C2", "L2"
CField = "C2"
LField = "L2"
RField = "R2"
RCatField = "RR2"




Case Else
Exit Sub
End Select

CText = Left(ActiveDocument.SelectContentControlsByTitle(CField).Item(1).Range.Text, 1)
LText = Left(ActiveDocument.SelectContentControlsByTitle(LField).Item(1).Range.Text, 1)
    If Not IsNumeric(CText) Then
With ActiveDocument.SelectContentControlsByTitle(RField)(1)
   .LockContents = False
   .Range.Text = ""
   .LockContents = True
End With
With ActiveDocument.SelectContentControlsByTitle(RCatField)(1)
   .LockContents = False
   .Range.Text = ""
   .LockContents = True
End With
      End If
        If Not IsNumeric(LText) Then
      Exit Sub
      End If
      LRate = LText
      CRate = CText
      RRate = ((CRate * 3) + (LRate * 2)) * 4
      Select Case RRate
      Case Is < 41
      RCat = "Low"
      Case Is < 55
      RCat = "Moderate"
      Case Is < 70
      RCat = "High"
      Case Is >= 70
        RCat = "Catastrophic"
      End Select




With ActiveDocument.SelectContentControlsByTitle(RField)(1)
   .LockContents = False
   .Range.Text = RRate
   .LockContents = True
End With
With ActiveDocument.SelectContentControlsByTitle(RCatField)(1)
   .LockContents = False
   .Range.Text = RCat
   .LockContents = True
End With
End Sub

1 个答案:

答案 0 :(得分:0)

尝试:

With ActiveDocument.SelectContentControlsByTitle(RCatField)(1)
  .LockContents = False
  .Range.Text = RCat
  With .Range.Cells(1).Shading
    Select Case RCat
      Case "Low": .BackgroundPatternColor = wdColorBrightGreen
      Case "Moderate": .BackgroundPatternColor = wdColorYellow
      Case "High": .BackgroundPatternColor = wdColorOrange
      Case "Catastrophic":: .BackgroundPatternColor = wdColorRed
      Case Else: .BackgroundPatternColor = wdColorAutomatic
    End Select
  End With
  .LockContents = True
End With