简体   繁体   English

基于单元格值创建 VBA 消息框

[英]Create a VBA Message Box Based on Cell Value

So, this should be fairly easy to implement, but I am unable to get the message box to display.所以,这应该很容易实现,但我无法显示消息框。

Context - this is for an estimation tool - if the user enters a value for a particular cell that is less than a minimum threshold, I want to bring up a message box to let them know that's not a valid entry.上下文 - 这是一个估计工具 - 如果用户为特定单元格输入一个小于最小阈值的值,我想显示一个消息框,让他们知道这不是一个有效的条目。

The cell I am referring to is named (let's just say TEST ).我所指的单元格被命名(让我们只说TEST )。 Its location is on the UI tab (1 of 4 tabs in the workbook) is row 47, column 17.它的位置在UI选项卡上(工作簿中的 4 个选项卡之一)是第 47 行第 17 列。

Here is the code I have tried so far:这是我到目前为止尝试过的代码:

Sub UI Alerts()
    If Cells(47, 17) < "1000" Then
        MsgBox ("Minimum Value is 1000")
        Exit Sub
    End If

Similarly, with the named cell同样,对于命名单元格

Sub UI Alerts()
    If ("TEST").value < "1000" Then
        MsgBox ("Minimum Value is 1000")
        Exit Sub
    End If

I have set this up in the VBA module that corresponds to the UI tab, so I shouldn't have to reference the sheet.我已经在对应于 UI 选项卡的 VBA 模块中进行了设置,因此我不必引用该工作表。 Any idea why the message box isn't displaying?知道为什么消息框没有显示吗? Is it possible to automatically display a message box based on a cell value?是否可以根据单元格值自动显示消息框?

Thanks.谢谢。

Unless there is a specific reason we need this to be a macro, it sounds like standard data validation would work for you here.除非有特定原因我们需要将其作为宏,否则听起来标准数据验证在这里对您有用。 Try this: select the cell you want the rules applied to, then on the ribbon/toolbar find Data > Data Validation.试试这个:选择你想要应用规则的单元格,然后在功能区/工具栏上找到数据 > 数据验证。 You can require a whole number greater than 1,000 (or a value in another cell), display a comment box with instructions when the user selects the cell, and an error message if an invalid number is entered.您可以要求大于 1,000 的整数(或另一个单元格中的值),在用户选择单元格时显示带有说明的注释框,如果输入了无效数字,则显示错误消息。

You need to use the Change event within the worksheet.您需要在工作表中使用 Change 事件。 Below is a sample code that should work with your named range.下面是一个适用于您的命名范围的示例代码。 At any rate, it should show you how to do so.无论如何,它应该告诉你如何做到这一点。

Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Address = Range("TEST").Address Then
        If Range("TEST").Value < 1000 Then
            MsgBox ("Minimum Value is 1000")
        End If
    End If
End Sub

You need to add your code to the Worksheet "Change" event.您需要将代码添加到工作表“更改”事件中。

Right now, you have code but it never gets called.现在,您有代码,但它永远不会被调用。

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

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