【问题标题】:Excel MsgBox with VBA for multiple linked range带有 VBA 的 Excel MsgBox 用于多个链接范围
【发布时间】:2017-05-19 22:42:11
【问题描述】:

我需要一些关于 excel 问题的帮助。

它是以下两个问题的组合:

1) Excel - Popup message with sound alert when cell value meets certain criteria

2) VBA code to show Message Box popup if the formula in the target cell exceeds a certain value

Sheet1 中,我有一系列产品和销售数据。 示例:Sheet1

Sheet2 中,我有多列 sumif() 函数。示例:Sheet2。 它包含 (A:A) 中的一列名称和 (B:B) 和 (C:C) 中的数据,这些数据链接到其他工作表中的单元格。当 B 列中任何单元格的值超过 20 或 C 列超过 40 时,我想要一个弹出通知说(“A 列中的文本”已售出 > 20)。

例如:如果“B”列中的一个单元格值更新为 33(>20)并且“A”列中相应的单元格值包含文本为“Charlie” , excel 表应该弹出消息说“查理出售是> 20”。

下面的 VBA 代码完成了这个如果它是原始数据。但是,当单元格链接到其他工作表中的数据时,它就不起作用了,就像这个工作簿一样。

Private Sub Worksheet_Change(ByVal Target As Range)
   If Target.column = 2 and target.value > 1 Then
       MsgBox target.offset(0,-1).text & " sold is > 20"
   End If
End Sub

此替代代码适用于从其他工作表链接的数据,但它仅适用于特定单元格,而不适用于整个列。

Private Sub Worksheet_Calculate()

If Sheets("Sheet2").Range("B2").Value > 20 Then
    MsgBox "B2 is >20", vbOKOnly
End If

End Sub

我想要实现的是这个:当我在 Sheet1 中输入我的原始数据时,Sheet2 列 (B:B) 和列 (C:C) 中的数字会得到更新。一旦 Sheet2 列 (B:B) 中的任何单元格超过 20 或列 (C:C) 超过 40,就会弹出通知链接回 A 列文本,例如 MsgBox target.offset(0,-1).text & " sold is > 20"。有没有办法结合上述两个代码来实现这一点? 也欢迎任何替代解决方案,谢谢!

【问题讨论】:

    标签: excel vba range msgbox


    【解决方案1】:

    比较汇总表中的所有总和

    Private Sub Worksheet_Calculate()
    
        Dim RangeToCheck As Range
        Dim Cell As Range
        Set RangeToCheck = Sheets("Sheet2").Range("B2:B5") 'See comment #1
    
        For Each Cell In RangeToCheck.Cells
            With Cell
                If .Value2 > 20 Then
                    MsgBox "Product: " & .Offset(columnoffset:=-1).Value2 & _
                    " in cell: " & .Address & " is " & .Value2 & ">20", vbOKOnly
                End If
            End With
        Next
    
    End Sub
    

    评论

    1. 我建议将 Sheet2 上的范围转换为 Excel 表格,并改用 ListObjectListcolumns
    2. 题外话提示:您也可以使用一些计数器,将范围放入VBA数组并循环遍历数组,这将比一个接一个地引用工作表单元格更快。见Writing efficient VBA UDFs (Part 1)

    【讨论】:

    • 非常感谢您的及时回答,这很好用!我也会努力落实您的建议。
    猜你喜欢
    • 1970-01-01
    • 2016-07-19
    • 2021-12-21
    • 2018-06-19
    • 2013-03-31
    • 2014-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多