工作表上的数据validation更改vba

我想在Excel中做一些数据validation,这将限制用户input基于以前的用户input。 我希望根据工作表的变化进行更新。 代码如下:

Private Sub Worksheet_Change(ByVal Target As Range) 'If Target.Cells.Count > 1 Then Exit Sub 'Checks if cell is Record or Assumption and applies appropriate data validation Dim Cell As Range Application.EnableEvents = False If Target.Column = 59 Or 72 Or 85 Or 98 Or 111 Then 'Refers to the columns that require Rec/Ass Set Cell = Target.Offset(0, 3) 'MsgBox Cell & " " & Target.Value 'USED TO ERROR CHECK If Target.Value = "N/A" Then Cell.Validation.Delete Cell.Value = vbNullString Cell.Offset(0, 1).Validation.Delete Cell.Offset(0, 1).Value = vbNullString Else If Target.Value = "Record" Then With Cell.Validation .Delete .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:=xlBetween, Formula1:="=Record" End With ElseIf Target.Value = "Assumption" Then Cell.Validation.Delete Cell.Value = vbNullString Cell.Offset(0, 1).Value = vbNullString End If End If Set Cell = ActiveCell End If If Target.Column = 62 Or 75 Or 88 Or 101 Or 114 Then 'Refers to the columns that require Doc Type Desig = Application.VLookup(Target.Value, Sheets("Record Source Chart").Range("RecordDesig"), 21, False) If Target.Value = "" Then Exit Sub Else Set Cell = Target.Offset(0, 1) With Cell.Validation .Delete .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:=xlBetween, Formula1:="=" & Desig End With End If Application.EnableEvents = True End Sub 

我有第二个if语句的问题。 当我运行这个代码时,第二个data.validation不会被添加 – 我认为这是因为单元格是空白的,直到我更新它,但即使我更新它,validation不会通过。 此外,如果我删除If Target.Value = "" Then Exit Sub即使Target.Column = 59,第二个if语句运行并返回“types不匹配”错误。 任何帮助非常感谢,谢谢。

改变这个:

 If Target.Column = 62 Or 75 Or 88 Or 101 Or 114 Then 

至 :

 If Target.Column = 62 Or Target.Column = 75 Or Target.Column = 88 Or Target.Column = 101 Or Target.Column = 114 Then 

或者更好的是, Select Case

 Select Case Target.Column Case 62, 75, 88, 101, 114 ' rest of your code goes here... End Select 

注意 :您还需要首次修改它:

 If Target.Column = 59 Or 72 Or 85 Or 98 Or 111 Then 'Refers to the columns that require Rec/Ass