VBA – 单元格更改

我需要用户在列C中插入是/否。如果否,下一个单元格应显示N / A并填写为灰色。 如果是的话,下一个单元格应该突出显示为黄色,并允许用户填写该单元格。

代码如下,但如果一个单元格没有,然后更改为是,下一个单元格不会从N / A更改为突出显示。

Private Sub Worksheet_Change(ByVal Target As Range) Dim Cell As Range If Target.Column = 3 Then Set Cell = Target.Offset(0, 1) If Len(Target.Value) = 0 Then Cell.Validation.Delete Cell.Value = vbNullString Else If Target.Value = "Yes" Then With Cell.Validation Cell.Interior.ColorIndex = 36 End With ElseIf Target.Value = "No" Then Cell.Validation.Delete Cell.Value = "N/A" Else MsgBox "Input only Yes or No." Target.ClearContents Cell.Validation.Delete End If End If End If End Sub 

这是因为您没有在if条件中为yes条件添加一行来更改相邻单元的值。 此外,对于no块,您可能想要将单元格的颜色更改为白色,否则一旦以前是yes,它就会保持黄色。 下面的代码应该达到你想要的。

 Private Sub Worksheet_Change(ByVal Target As Range) Dim Cell As Range If Target.Column = 3 Then Set Cell = Target.Offset(0, 1) If Len(Target.Value) = 0 Then Cell.Validation.Delete Cell.Value = vbNullString Else If Target.Value = "Yes" Then With Cell.Validation Cell.Interior.ColorIndex = 36 End With Cell.Value = "" ElseIf Target.Value = "No" Then Cell.Validation.Delete Cell.Value = "N/A" Cell.Interior.ColorIndex = 0 Else MsgBox "Input only Yes or No." Target.ClearContents Cell.Validation.Delete End If End If End If End Sub 

尝试

 If target.value = "yes" then cell.validation.delete cell.interior.color = vbyellow cell.clearcontents end if 
  • 清除单元格的内容时,需要打开EnableEvents。 这样Worksheet_Change不会再被触发。 否则,你会陷入一个循环。
  • 您没有使用Excel内build的单元validation,您正在进行validation
  • 你想要做什么可以和应该使用Excel的内置单元格validation和条件格式。

    • 如果用户影响多个单元格的单元格值,此方法将失败,单元格validation和条件格式化仍将正常工作。

    私人小组Worksheet_Change(BYVAL目标作为范围)昏暗的单元格作为范围

     If Target.Column = 3 Then Application.EnableEvents = False Set Cell = Target.Offset(0, 1) With Cell.Interior If Target.Value = "Yes" Then 'Change Cell Color to Yellow .ColorIndex = 36 ElseIf Target.Value = "No" Then 'Change Cell Color to Grey ' Insert Grey Color Change Cell.Value = "N/A" Else Target.ClearContents Cell.ClearContents With Cell.Interior .Pattern = xlNone .TintAndShade = 0 .PatternTintAndShade = 0 End With MsgBox "Input only Yes or No." End If End With Application.EnableEvents = True End If 

    结束小组

您可以使用MsgBox询问他们是否希望值是或不是。

 iResponse = MsgBox("Input only Yes or No.", vbYesNoCancel) Select Case iResponse Case vbYes Target.Value = "Yes" Case vbNo Target.Value = "Yes" Case Else 'You need to turn of Events when clearing the cell 'So that the Worksheet_Change won't fire again Application.EnableEvents = False Target.ClearContents Cell.ClearContents End Select