显示多个错误时采用行号的消息框

Message box to take the row number when multiple errors are shown

每次在 "W" 列中插入文本时,我都会使用此代码接收错误消息。当发生这种情况时,文本将被删除并出现一条框消息:"The row W" & r & " must contain only digits!" 告诉错误的行号。 r - 设置为 Target.Row

我的问题是,当我复制 w10:w12 范围内的文本时,我收到了 3 次错误消息,这很好。但是,在消息框中它仅显示行号 w10 - 3 次,即“The row W10 must contain only digits!”。我怎样才能使代码显示消息框先是 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

[...] 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)完成所有这些操作,但实际上根本没有必要。

首先获取相交范围然后检查那些单元格会更容易:

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