根据另一列上的IF语句在Msgbox中显示单元格值-Excel VBA

问题描述 投票:2回答:2

我想创建一个Msgbox警报,以告诉我员工合同的终止时间。

到期日为4-1个月的合同的单元格将用红色填充:

enter image description here

到目前为止,这是我的代码:

Private Sub workbook_open()

Dim rngData As Range
Dim rngCell As Range
Dim counter As Long: counter = 0
Set rngData = Range("E4:E" & Cells(Rows.Count, Range("E3").Column).End(xlUp).Row)


For Each rngCell In rngData
    If rngCell.Value = "4" Or rngCell.Value = "3" Or rngCell.Value = "2" Or rngCell.Value = "1" And rngCell.Value <> "" Then

        counter = counter + 1
    End If
Next rngCell
MsgBox counter & " employees are reaching their contract expiration date!"

Range("A4:E13").Sort _
Key1:=Range("E4"), Order1:=xlAscending


End Sub

但是,我如何包含一行代码来告诉我其合同即将到期的员工的EE号,也将显示在Msgbox中?

excel vba excel-2010
2个回答
2
投票

构建要在找到它们时显示的字符串

Dim str As String
For Each rngCell In rngData
    If rngCell.Value <> "" And rngCell.Value <= 4 Then
       str = str & vbCr & rngCell.Offset(0, -4).Value
       counter = counter + 1
    End If
Next rngCell
MsgBox counter & " employees are reaching their contract expiration date!" & str

1
投票

您还可以只构建一个字符串列表以在循环结束时显示。

Private Sub workbook_open()
    Dim rngData As Range
    Dim rngCell As Range
    Dim expired As String
    Dim counter As Long: counter = 0
    Set rngData = Range("E4:E" & Cells(Rows.Count, Range("E3").Column).End(xlUp).Row)
    For Each rngCell In rngData
        If rngCell.Value = "4" Or rngCell.Value = "3" Or _
           rngCell.Value = "2" Or rngCell.Value = "1" And rngCell.Value <> "" Then
            counter = counter + 1
            '--- add to the list of expired EE Numbers
            expired = expired & rngCell.Offset(0, -4).Value & ","
        End If
    Next rngCell
    expired = Left$(expired, Len(expired) - 1)   'delete the trailing comma
    MsgBox counter & " employees are reaching their contract expiration date! (" & _
           expired & ")"
    Range("A4:E13").Sort Key1:=Range("E4"), Order1:=xlAscending
End Sub
© www.soinside.com 2019 - 2024. All rights reserved.