VBA如何检查单元格范围的值并插入数据验证列表

时间:2013-11-20 19:21:45

标签: vba excel-vba excel-2007 excel

我希望下面的代码在“B5:B61”范围内插入一个数据验证列表,其中包含“new_DDM3”源,其中单元格的值是“选择”。

当“B2”中的选择发生变化时会发生这种情况。

 Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)

If Target.Address = "$B$2" Then
With Range("B5")
    .Formula = "=myformula"
    .Value = .Value
If Range("B5") = "Choose" Then
With .Validation
    .Delete
    .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
    xlBetween, Formula1:="=new_DDM3"
    .IgnoreBlank = True
    .InCellDropdown = True
    .InputTitle = ""
    .ErrorTitle = ""
    .InputMessage = ""
    .ErrorMessage = ""
    .ShowInput = True
    .ShowError = True


End With
End If
End With
End If
End Sub

非常感谢任何建议!

1 个答案:

答案 0 :(得分:0)

如果你想在B5:B61中的所有单元格中运行相同的代码,那么你可以使用循环

For Each cell in Range("B5:B61").Cells
    With cell
        .Formula = "=myformula"
        .Value = .Value
    If cell = "Choose" Then
    With .Validation
        .Delete
        .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
        xlBetween, Formula1:="=new_DDM3"
        .IgnoreBlank = True
        .InCellDropdown = True
        .InputTitle = ""
        .ErrorTitle = ""
        .InputMessage = ""
        .ErrorMessage = ""
        .ShowInput = True
        .ShowError = True    
    End With
next cell