【问题标题】:VBA Code MsgBox if 2 criteria for each row in tableVBA代码MsgBox,如果表中每一行有2个标准
【发布时间】:2019-01-08 02:50:55
【问题描述】:

我有一个代码可以查找 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 行的整个表,并且理想情况下继续查看表是否针对每一行的特定条件变大,所有 A2B2A3B3 等等。 目前它只查看我选择的单元格,我能想到的唯一解决方案是复制粘贴并更改每段新代码的范围。

谢谢!

【问题讨论】:

  • If Range("A" & Target.Row).Value = "Text1" And Range("B" & Target.ROW).Value > ### Then MsgBox "Message"`
  • 您也可能想使用Target.Cells.CountLarge 而不是.Count?请看This
  • 您所描述的内容需要一个 For ... Next 循环。在 MSDN 或他们教的地方查找。但是,从逻辑上讲,这在 Change 事件中没有意义,因为一次只更改了一项,并且您不需要检查那些未更改的项目,因为它们之前已被检查过。要创建动态范围,请查看 Cells(Rows.Count, "A").End(xlUp).Row
  • @Variatus:当您粘贴到相关范围内的多个单元格上时,这些更改也会发生。但是Target.Cells.CountLarge/Target.Cells.Count 会否定它。
  • @SiddharthRout,太完美了!太感谢了!先生,您解决了我的问题。

标签: excel vba msgbox


【解决方案1】:

只需遍历 A 列和 B 列:

Option Explicit
Sub LookUpWithMessageBox()
    Dim lastRow As Long, i As Long
    lastRow = Cells(Rows.Count, 1).End(xlUp).Row
    For i = 1 To lastRow
        If Cells(i, 1).Value = "column A criteria" And Cells(i, 2).Value = "column B criteria" Then MsgBox Cells(i, 1).Value & " " & Cells(i, 2).Value
    Next
End Sub

【讨论】:

    【解决方案2】:

    你可以试试这个:

    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
    

    图纸结构:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-07
      • 2017-10-17
      • 1970-01-01
      • 1970-01-01
      • 2019-02-15
      • 2021-03-09
      相关资源
      最近更新 更多