在Excel中,限制单元格范围内的字符总数(例如1000)

时间:2018-08-09 16:21:06

标签: excel excel-vba excel-formula

我希望工作簿用户在一定范围的单元格中不能超过1000个字符(例如:A5:A30)。换句话说,将总字符数限制在A5:A30到1000个字符之间。

1 个答案:

答案 0 :(得分:2)

当用户填写一个发送范围超过1000个字符限制的单元格时,它将调用Application.undo,该命令应删除他们添加的最后一个文本。

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