jusbruers
jusbruers

Reputation: 3

Modify Macro to apply to single column

I have a macro sub that I want to only apply to a single column (F), rather than a whole sheet, so the users don't get the error message when they are inputting data other that the size code.

This is what I have:

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

If I'm inputting data in any other column, I'm still getting the MsgBox.

Upvotes: 0

Views: 35

Answers (1)

tigeravatar
tigeravatar

Reputation: 26640

Refactored code, something like this should work for you:

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

Upvotes: 1

Related Questions