繁体   English   中英

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

[英]How to Display a message box in excel vba when value in a cell exceeds another?

当单元格G27的值超过单元格K13的值时,我需要显示一个消息框。 我要求在单元格G27填满后立即显示。 我已经尝试了以下宏,但是它不起作用。

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

任何帮助深表感谢!

这是您要尝试的吗? 未经测试 ),也可以理解,你必须在表代码区域的代码,而不是一个模块:)

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

您也可以尝试这样做(数据验证):

With Sheets("WorksheetName"). Range("G27").Validation如果在Private Sub Workbook_Open()或任何标准模块下使用,则进行Range("G27").Validation 如果在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

仅供参考:可以在不使用vb​​a的情况下使用数据验证,即直接从excel中使用。 您可以选择AlertStyle(信息,警告,停止)和Input Title。 请参阅http://office.microsoft.com/en-001/excel-help/apply-data-validation-to-cells-HP010342173.aspx

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM