将多个MsgBox合并为一个

时间:2016-02-04 18:40:07

标签: excel-vba vba excel

当我们打开此工作簿时,此代码将查看范围并查找包含文本“RCA Pending”的单元格,并将弹出一个MsgBox,让用户知道该列中的哪一行包含特定文本。问题是,如果有多行包含此文本,则还会有多个MsgBox弹出窗口。

Private Sub Auto_Open()

Dim i As Variant
Dim FindRange As Range
Set FindRange = Range("AB2:AB2000")

    For Each i In FindRange
        If i = "RCA Pending" Then

        MsgBox "Found 'RCA Pending' in cell" & " " & i.Address, vbExclamation, "Attention"

        End If
    Next i
End Sub

此代码中需要更改哪些内容,以便只有一个弹出窗口列出找到“RCA Pending”的所有行?

2 个答案:

答案 0 :(得分:3)

试试这段代码:

Private Sub Auto_Open()    

Dim i As Variant
Dim FindRange As Range
Dim Msg As String
Set FindRange = Range("AB2:AB2000")

    For Each i In FindRange
       If i = "RCA Pending" Then

        If Msg = "" Then
         Msg = "Found 'RCA Pending' in cell" & " " & i.Address
        Else
         Msg = Msg & Chr(10) & "Found 'RCA Pending' in cell" & " " & i.Address
        End If

       End If
    Next i
    If Msg <> "" Then MsgBox Msg, vbExclamation, "Attention"
End Sub

答案 1 :(得分:2)

试试这个,

Sub Msgbox_It()

    Dim sh As Worksheet
    Dim LstRw As Long
    Dim i As Range
    Dim FindRange As Range
    Dim Msg As String

    Set sh = Sheets("Sheet1")    'name of worksheet
    With sh
        LstRw = .Cells(.Rows.Count, "AB").End(xlUp).Row
        Set FindRange = .Range("AB2:AB" & LstRw)

        For Each i In FindRange
            If i = "RCA Pending" Then
                Msg = Msg & i.Address & vbNewLine
            End If
        Next i

        MsgBox "Found 'RCA Pending' in cell" & " " & Msg, vbExclamation, "Attention"
    End With
End Sub