VBA中的数据验证列表运行宏

时间:2018-10-25 10:13:47

标签: excel vba excel-vba

我正在尝试从数据验证列表中运行宏(对于测试只是提示一个消息框),该数据验证列表是在每次运行创建新行的宏时创建的。新行在第6行中创建,数据验证列表始终在F6中。 当我添加新行时,这将改变路线并向下移动旧行。

当“ F”列中的任何数据验证列表发生更改时,我想运行一个新的宏。

现在我有了这段代码,但是它一直在提示

“运行时错误'13':类型不匹配”

我创建验证列表的模块如下所示:

With Range("F6").Validation
    .Delete
    .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
    Operator:=xlBetween, Formula1:="High,Medium,Low"
    .IgnoreBlank = True
    .InCellDropdown = True
    .InputTitle = ""
    .ErrorTitle = ""
    .InputMessage = ""
    .ErrorMessage = ""
    .ShowInput = True
    .ShowError = True
End With

在sheet1中,我需要更改以下代码:

Sub Worksheet_Change(ByVal Target As Range)

Dim d As Range
Set d = Application.Intersect(Target.Cells(1), Me.Range("F5:F1000"))
    If Not Range("F5:F1000") Is Nothing Then
        Select Case Columns(2)
            Case "High": MsgBox ("Test")
            Case "Medium": MsgBox ("Test")
            Case "Low": MsgBox ("Test")
        End Select
        Else
                    'do nothing
    End If

有人可以发现错误吗?

Screenshot

-CP

1 个答案:

答案 0 :(得分:0)

也许您正在追求:

Sub Worksheet_Change(ByVal Target As Range)
    Dim d As Range

    Set d = Application.Intersect(Target.Cells(1), Range("F5:F1000")) 
    If Not d Is Nothing Then ' <<---check if set range is nothing
        Select Case Target.Value2 ' <<-- check changed cell (i.e. 'Target') value
            Case "High": MsgBox "High" & " in " & Target.Address
            Case "Medium": MsgBox "Medium" & " in " & Target.Address
            Case "Low": MsgBox "Low" & " in " & Target.Address
        End Select
    End If
End Sub