VBA代码MsgBox,如果表中的每一行有2条条件

时间:2019-01-08 02:50:56

标签: excel vba msgbox

我有一个代码,该代码可以查找2个不同的单元格,并且每当两个单元格都具有特定条件时都会显示一个弹出窗口,但是它仅针对该特定行。

我正在寻找一种拥有1个代码的方法,该代码将查找每行中的每对单元格并独立地对其进行评估。

尝试更改范围,但显然会创建较长的代码,我敢肯定有更好的方法,但是我的知识有限。

Private Sub Worksheet_Change(ByVal Target As Range)

    If Target.Count > 1 Then Exit Sub
    If Not Application.Intersect(Target, Me.Range("A:B")) Is Nothing Then
         If (Range("A2").Value = "Text1") And Range("B2").Value > ### Then MsgBox "Message"

End If

End Sub

代码应查看200行的整个表,并且理想情况下应继续查看表是否针对每行(所有A2B2A3和{ {1}},依此类推。 目前,它仅查看我选择的单元格,我能想到的唯一解决方案是复制粘贴并更改每个新代码段的范围。

谢谢!

2 个答案:

答案 0 :(得分:0)

仅循环访问A和B列:

C

答案 1 :(得分:0)

您可以尝试以下方法:

Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)

    Dim rngTable As Range
    Dim Lastrow As Long

    With ActiveSheet
        'Calculate table last row
        Lastrow = .Cells(.Rows.Count, "A").End(xlUp).Row
        'Set rng to search (FROM Column A row 2 TO Column B row 5)
        Set rngTable = .Range(Cells(2, 1), Cells(Lastrow, 2))
        'Check if tha target included in the table
        If Not Intersect(Target, rngTable) Is Nothing Then
            'Check if the target and the cell next to it are equal
            If Target.Value = Target.Offset(0, -1).Value Then
                'if both cells are equal meesage with there address will appear
                MsgBox "Cells " & Replace(Target.Offset(0, -1).Address, "$", "") & " and " & Replace(Target.Address, "$", "") & " are the same!"
            End If

        End If
    End With

End Sub

表单结构:

enter image description here