当单元格中的值超过另一个时,如何在excel vba中显示消息框?

时间:2014-11-27 08:01:18

标签: excel excel-vba vba

当单元格G27中的值超过单元格K13中的值时,我需要显示一个消息框。一旦G27格栅填满,我就要求它出现。我尝试了以下宏,但它无法正常工作。

Private Sub Worksheet_Change(ByVal Target As Range)
    If Range("G27") > Range("K13") Then
        MsgBox "error"
    End If
End Sub

非常感谢任何帮助!

2 个答案:

答案 0 :(得分:0)

这是你在尝试什么? ( UNTESTED )另外,您可以理解在“工作表代码”区域中有此代码,而不是模块:)

Private Sub Worksheet_Change(ByVal Target As Range)
    On Error GoTo Whoa

    Application.EnableEvents = False

    If Not Intersect(Target, Range("G27")) Is Nothing Then _
    If Range("G27").Value > Range("K13").Value Then MsgBox "error"

Letscontinue:
    Application.EnableEvents = True
    Exit Sub
Whoa:
    MsgBox Err.Description
    Resume Letscontinue
End Sub

有关Worksheet_Change HERE

的更多信息

答案 1 :(得分:0)

你也可以试试这个(数据验证):

With Sheets("WorksheetName").之前使用Range("G27").Validation,如果在Private Sub Workbook_Open()下使用,或者在任何标准模块下使用Private Sub Worksheet_Activate()。如果在With Range("G27").Validation .Delete .Add Type:=xlValidateWholeNumber, AlertStyle:=xlValidAlertStop, _ Operator:=xlLessEqual, Formula1:="=K13" .IgnoreBlank = True .InCellDropdown = True .InputTitle = "Input Title" .ErrorTitle = "Error Title" .InputMessage = "Input Msg" .ErrorMessage = "Error Msg" .ShowInput = True .ShowError = True End With

下使用,请按以下方式使用
{{1}}

供参考: 数据验证可以在没有vba的情况下使用,即直接来自excel。您可以选择AlertStyle(信息,警告,停止)和输入标题。见http://office.microsoft.com/en-001/excel-help/apply-data-validation-to-cells-HP010342173.aspx