修改宏以应用于单列

时间:2018-09-13 18:47:31

标签: excel vba

我有一个宏子,只想应用于单列(F),而不是整个工作表,因此用户在输入尺寸代码以外的数据时不会收到错误消息。

这就是我所拥有的:

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim A As Range, r As Range
    vars1 = Array("xs", "s", "m", "l", "xl", "xxl", "1x", "2x", "3x", "os", "s/m", "l/xl")
    Set A = Range("F:F")
        Set Target = A
       For Each r In Target
        If IsNumeric(Application.Match(LCase(r.Value), vars1, 0)) Then
        Exit Sub
        Else
            MsgBox "Invalid Size entered into cell " & r.Address
        End If
        Next r
End Sub

如果我在其他任何列中输入数据,则仍会收到MsgBox。

1 个答案:

答案 0 :(得分:1)

重构代码,类似这样的代码应该对您有用:

Private Sub Worksheet_Change(ByVal Target As Range)

    Dim rCheck As Range
    Dim rInvalids As Range
    Dim r As Range

    vars1 = Array("xs", "s", "m", "l", "xl", "xxl", "1x", "2x", "3x", "os", "s/m", "l/xl")

    Set rCheck = Intersect(Target, Me.Columns("F"))
    If Not rCheck Is Nothing Then
        For Each r In rCheck.Cells
            If Not IsNumeric(Application.Match(LCase(r.Value), vars1, 0)) Then
                If rInvalids Is Nothing Then
                    Set rInvalids = r
                Else
                    Set rInvalids = Union(rInvalids, r)
                End If
            End If
        Next r
        If Not rInvalids Is Nothing Then MsgBox "Invalid Size entered into cell " & rInvalids.Address
    End If

End Sub