Home » excel » In Excel, limit the total number characters (like 1000) in a range of cells

In Excel, limit the total number characters (like 1000) in a range of cells

Posted by: admin May 14, 2020 Leave a comment

Questions:

I am looking to limit my workbook users to 1000 characters over a range of cells (Example: A5:A30). In other words limit the total characters in the range A5:A30 to 1000 characters.

How to&Answers:

When a user fills in a cell that sends the range over the 1000 character limit, it will call Application.undo which should just remove the last text that they added.

Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)

    If Not Intersect(Target, Range("A5:A30")) Is Nothing Then

        Dim charCount As Long

        Dim arrValues As Variant
        arrValues = Range("A5:A30").Value2

        Dim i As Long
        Dim tempSplit As Variant
        Dim j As Long

        For i = LBound(arrValues) To UBound(arrValues)
            tempSplit = Split(arrValues(i, 1), " ")

            For j = LBound(tempSplit) To UBound(tempSplit)
                charCount = charCount + Len(tempSplit(j))
            Next j
        Next i

        If charCount > 1000 Then
            With Application
                .EnableEvents = False
                .Undo
                .EnableEvents = True
            End With

            MsgBox "Adding this exceeds the 1000 character limit"
        End If

    End If

End Sub