特定列的单元格更改时显示消息

时间:2017-12-01 07:24:28

标签: excel vba excel-vba

我是Excel VBA的新手。我想在K列中的任何单元格更改时显示警告消息。我写了这段代码:

Private Sub Worksheet_Change(ByVal Target As Range)

    Dim row As Integer
    Dim lrow As Long
    With ActiveSheet
        lrow = .Range("K" & .Rows.Count).End(xlUp).row

        For satir = 5 To lrow
            If Cells(row, 11).Value > 400 And Cells(row, 12).Value = "" Then
                MsgBox _
                ("Risk Point of your operation is still high, Please Identify Contingency Plan")
            End If
        Next row

        For row = 5 To lrow
            If Cells(row, 22).Value > 200 And Cells(row, 24).Value = "" Then
                MsgBox ("Risk Point is very high, Please Identify your Mitigation Plan")
            End If
        Next row
    End With

End Sub

此代码正在运行,但会对工作表中所做的所有更改显示警告消息。

2 个答案:

答案 0 :(得分:3)

将此内容写入您的Worksheet_Change Sub:

 If Target.Column = 11 Then
    MsgBox "warning"
 End If

这将发送"警告"只要用户更改了第k列中的值

答案 1 :(得分:1)

这是重构您的代码。 This answer by C. Henke已经回答了您的问题。

Dim row As Long '~~> use long to avoid overflow
Dim lrow As Long, satir As Long

With Me '~~> to refer to the worksheet itself, you can use Me object

    If Not Intersect(.Range("K:K"), Target) Is Nothing Then
    '~~> check if target cell reside in K column
        lrow = .Range("K" & .Rows.Count).End(xlUp).row
        For satir = 5 To lrow
            If .Cells(row, 11).Value > 400 _
            And .Cells(row, 12).Value = "" Then
                MsgBox "Risk Point of your operation is still high." & _
                vbNewLine & "Please Identify Contingency Plan"
            End If
        Next satir

        For row = 5 To lrow
            If .Cells(row, 22).Value > 200 _
            And .Cells(row, 24).Value = "" Then
                MsgBox "Risk Point of your operation is still high." & _
                vbNewLine & "Please Identify Contingency Plan"
            End If
        Next row
    End If

End With

希望这能让你前进。