每次在“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
最佳答案
[...] to receive an error message every time when in column "W" a text is inserted. When this happens the text is deleted and a box message appears:"The row W" & r & " must contain only digits!"
正确的做法是使用 数据验证以限制单元格可以采用的可能值。
您可以指定 Excel 在给定无效值的情况下显示的错误消息:
...甚至在选择单元格时出现工具提示消息:
在这里,我为单元格 A1 配置了数据验证:
您可以使用 VBA 代码完成所有这些操作(使用
Range.Validation
API),但实际上根本不需要。
关于vba - 显示多个错误时获取行号的消息框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47759710/