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

时间:2017-12-11 19:08:25

标签: excel vba excel-vba row-number msgbox

每次在“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

3 个答案:

答案 0 :(得分:2)

  

[...]每次在“W”列中插入文本时都会收到错误消息。当发生这种情况时,文本被删除并出现一个框消息:“W行”和r& “必须只包含数字!”

正确的做法是使用数据验证,以限制单元格可以采用的值。

data validation setup dialog

您可以指定Excel显示给出无效值的错误消息:

validation error setup

...甚至在选择单元格时出现工具提示消息:

data validation tooltip setup

这里我为单元格A1配置了数据验证:

invalid valie!

您可以使用VBA代码(使用Range.Validation API)完成所有这些操作,但实际上根本不需要。

答案 1 :(得分:1)

 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

答案 2 :(得分:1)

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

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