我正在根据单元格值添加数据验证列表。如果单元格B29中的值=“text1”,则在单元格D29中添加数据验证。如果单元格B29具有不同的值,则必须将公式添加到单元格D29,并且必须删除数据验证。
以下是宏的示例:
If Range("B29").Value = "Text1" Then
Range("D29").Value = ""
With Selection.Validation
.Delete
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
xlBetween, Formula1:="=INDIRECT(B29)"
.IgnoreBlank = True
.InCellDropdown = True
.InputTitle = ""
.ErrorTitle = ""
.InputMessage = ""
.ErrorMessage = ""
.ShowInput = True
.ShowError = True
End With
ElseIf Range("B29").Value = "Value1" Then
Range("D29").Formula = "=IF(Sheet2!B9,VLOOKUP(Sheet2!B8,'Team Target Tabel'!C2:E17,2,FALSE),"""")"
Range("D29").Validation.Delete
ElseIf Range("B29").Value = "Value2" Then
Range("D29").Formula = "=IF(Sheet2!B9,VLOOKUP(Sheet2!B8,'Team Target Tabel'!C2:E17,2,FALSE),"""")"
Range("D29").Validation.Delete
ElseIf Range("B29").Value = "Value3" Then
Range("D29").Formula = "=IF(Sheet2!B9,VLOOKUP(Sheet2!B8,'Team Target Tabel'!C2:E17,2,FALSE),"""")"
Range("D29").Validation.Delete
End If
End Sub
Cell B29也是一个数据验证单元,它有4个值。如果值为text1,则单元格D29必须更改为数据验证列表,但我必须手动运行宏才能执行此操作。当D29是数据验证列表并且我更改单元格B29中的值时,我必须再次(手动)运行宏以将其更改回公式。
答案 0 :(得分:1)
您可以捕获Worksheet_change事件,以便在D29
更改时重新运行宏。
Private Sub Worksheet_Change(ByVal Target As Range)
If Not Intersect(Target, Me.Range("B29")) Is Nothing Then
Call myMacroToChangeValidationOfD29
End If
End Sub
BTW,为什么With Selection.Validation
不是With Range("D29").Validation
??
答案 1 :(得分:0)
我会使用StrComp比较字符串,例如:
If StrComp(Range("B29").Value, "text1") = 0 Then
'Something
End If
您想要针对“text1”检查B29,但是,您要针对“Text1”进行检查。您可能遇到区分大小写的问题。您的其他情况类似,您可以将它们简化为单个其他情况,如下所示:
If StrComp(Range("B29").Value, "text1") = 0 Then
Range("D29").Value = ""
With Selection.Validation
.Delete
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
xlBetween, Formula1:="=INDIRECT(B29)"
.IgnoreBlank = True
.InCellDropdown = True
.InputTitle = ""
.ErrorTitle = ""
.InputMessage = ""
.ErrorMessage = ""
.ShowInput = True
.ShowError = True
End With
Else
Range("D29").Formula = "=IF(Sheet2!B9,VLOOKUP(Sheet2!B8,'Team Target Tabel'!C2:E17,2,FALSE),"""")"
Range("D29").Validation.Delete
End Sub