我正在尝试在excel中进行一些数据验证,这会根据以前的用户输入限制用户输入。我希望根据工作表更改来更新。代码如下:
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没有被添加 - 我认为这是因为在我更新它之前单元格是空白的,但即使在我更新它之后,验证也不会通过。此外,如果我删除If Target.Value = "" Then Exit Sub
,即使Target.Column = 59,第二个if语句也会运行并返回" Type Mismatch"错误。非常感谢任何帮助,谢谢。
答案 0 :(得分:0)
改变这个:
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