当显示多个错误时,消息框取得行号
每次在列“W”中插入文本时,我都使用此代码来接收错误消息。 发生这种情况时,文本被删除,并出现一个信息框: “W行&r&”只能包含数字!“ 它告诉错误的行号。 r – 被设置为Target.Row
我的问题是,当我复制w10:w12范围内的文本时,我收到错误消息3次,这很好。 但在消息框中,它只显示行号w10 – 3次,即“ 行W10必须只包含数字! ”。 我怎样才能让代码显示消息框w10,然后w11,最后是w12?
Private Sub Worksheet_Change(ByVal Target As Range) Dim cell As Range Dim r As Long r = Target.Row Application.EnableEvents = False For Each cell In Target If Not Application.Intersect(cell, Range("w10:w10000")) Is Nothing Then If Not IsNumeric(cell.Value) Then MsgBox "The row W" & r & " must contain only digits!" cell.Value = vbNullString End If End If Next cell Application.EnableEvents = True
Private Sub Worksheet_Change(ByVal Target As Range) Dim cell As Range Application.EnableEvents = False For Each cell In Target If Not Application.Intersect(cell, Range("w10:w10000")) Is Nothing Then If Not IsNumeric(cell.Value) Then MsgBox "The row W" & cell.row & " must contain only digits!" cell.Value = vbNullString End If End If Next cell Application.EnableEvents = True
每次在列“W”中插入文本时都会收到错误消息。 发生这种情况时,文本被删除,并出现一个信息框:“W行&r&”只能包含数字!“
这里要做的正确的事情是使用数据validation来限制单元格可能的值。
您可以指定一个Excel显示的错误消息给出一个无效的值:
…甚至是在选中单元格时的工具提示消息:
在这里我为单元格A1configuration了数据validation:
您可以使用VBA代码(使用Range.Validation
API)来完成所有这些工作,但实际上完全没有必要。
先得到相交的范围然后检查这些单元格会更容易:
Sub F() Dim cell As Range Dim rngArea As Range Dim rngIntersect As Range Set rngIntersect = Intersect(Selection, [W10:W10000]) If rngIntersect Is Nothing Then Exit Sub For Each rngArea In rngIntersect.Areas For Each cell In rngArea '// The code... Next Next End Sub