Excel数据validation(文本长度)

这可能必须是在VBA中完成的,这很好。

一些背景信息:我想在Excel的数据validation中使用文本长度选项。 我需要限制为60个字符或更less。 然而,这是很容易的部分。

我的问题是,如果用户超过了这个60个字符的阈值,我不希望我的错误警报保持静态,并给出一个普遍的答复,说:“你必须保持在60个字符以下…”我希望它实际上计数用户尝试放置在单元格中的字符,然后在错误警报popup窗口中,我希望它是更具体的,如: You have exceeded the 60-character limit by ## characters. Please shorten the input and try again. You have exceeded the 60-character limit by ## characters. Please shorten the input and try again. 任何人都知道解决scheme?

我写了类似K Davis提供的代码的另一个答案。 除了编码风格之外,这里还有主要的function差异。

•处理多个目标列
•将地址添加到消息
•通知后selectstream氓小区
•向后循环,以便在发生多次恶意input时,用户首先结束
•variables的声明和赋值在实际需要时保留
•关键停止消息框

 Option Explicit Private Sub Worksheet_Change(ByVal Target As Range) If Not Intersect(Target, Union(Columns("B"), Columns("D"))) Is Nothing Then On Error GoTo bm_Safe_Exit Application.EnableEvents = False Dim mssg As String, iLimit As Long, a As Long, t As Long, trgt As Range iLimit = 60 Set trgt = Intersect(Target, Union(Columns("B"), Columns("D"))) 'loop backwards through multiples so we end up at the first rogue entry For a = trgt.Areas.Count To 1 Step -1 For t = trgt.Areas(a).Cells.Count To 1 Step -1 If Len(trgt.Areas(a).Cells(t).Value2) > iLimit Then mssg = "You have exceeded the " & iLimit & "-character limit by " & _ Len(trgt.Areas(a).Cells(t).Value2) - iLimit & " characters in " & _ trgt.Areas(a).Cells(t).Address(0, 0) & ". Please shorten the input and try again." MsgBox mssg, vbCritical + vbOKOnly, "Bad Input" trgt.Areas(a).Cells(t).ClearContents: trgt.Areas(a).Cells(t).Select End If Next t Next a Set trgt = Nothing End If bm_Safe_Exit: Application.EnableEvents = True End Sub 

text_length_validation

你可能想用一个或两个vbLF分割句子。 在我看来,这使得警报信息更加有效。 特别是在添加了单元地址的情况下。

我曾想过把所有的stream氓input单元格地址放在一个单独的消息中,但是这样会排除特定的透支字符数。


样品文本由Lorem Ipsum Generator提供

由于Jeepeed提出的build议,我进行了互联网search,偶然发现了这个网站 。 我已经修改了这个人的代码来完成我原来的问题所需要的东西,并希望在任何人遇到同样的问题时分享它。

这里是代码:

 Private Sub Worksheet_Change(ByVal Target As Range) Dim rng As Range Dim rCell As Range Dim iChars As Integer On Error GoTo ErrHandler 'Change these as desired iChars = 60 Set rng = Me.Range("B:B") If Not Intersect(Target, rng) Is Nothing Then Application.EnableEvents = False For Each rCell In Intersect(Target, rng) If Len(rCell.value) > iChars Then MsgBox "You have exceeded the 60-character" & _ " limit by " & Len(rCell.value) - iChars & _ " characters." & vbCrLf & "Please shorten" & _ " your input and try again.", vbRetryCancel End If Next End If ExitHandler: Application.EnableEvents = True Set rCell = Nothing Set rng = Nothing Exit Sub ErrHandler: MsgBox Err.Description Resume ExitHandler End Sub 

我认为在单元格旁边使用Excel公式会更好:

 = IF( LEN( B2 ) > 60, "You have exceeded the 60-character limit by " & ( LEN( B2 ) - 60 ) & " characters. Please shorten your input and try again.", "" )