使用vba查找相同值的开始日期和结束日期

时间:2015-05-06 05:46:43

标签: excel vba excel-vba

我的Excel表格如下所示。我想要一个任务的开始日期和结束日期。例如:对于ABC任务,开始日期为“2015-04-01”,结束日期为“2015-04-04”。如何总结日期?

Row# | Date       |Task
-----+------------+-----
1    | 2015-04-01 | ABC  
2    | 2015-04-02 | ABC
3    | 2015-04-05 | 123
4    | 2015-04-01 | 123
5    | 2015-04-04 | ABC
6    | 2015-04-01 | 123
7    | 2015-04-05 | 123
8    | 2015-04-01 | ABC

2 个答案:

答案 0 :(得分:0)

如果你懒得自己想出一个VBA代码,可以尝试使用它。有数据表。

Row# | Date       |Task | Date2
-----+------------+-----+----------------
1    | 2015-04-01 | ABC | =A2 [2015-04-01]
2    | 2015-04-02 | ABC | 
3    | 2015-04-05 | 123 | 
4    | 2015-04-01 | 123 | 
5    | 2015-04-04 | ABC | 
6    | 2015-04-01 | 123 | 
7    | 2015-04-05 | 123 | 
8    | 2015-04-01 | ABC | 

输出轴将如下所示:

Row# | Task | Min / Date | Max / Date2
-----+------+------------+-------------
1    | 123  | 2015-04-01 | 2015-04-05
2    | ABC  | 2015-04-01 | 2015-04-04

答案 1 :(得分:0)

下一步可以改进,但它有效:

Sub Fechas()
        Dim startDate As Date
        Dim endDate As Date        
        Dim selected As String
        startDate = #1/1/2999#
        endDate = #1/1/1900#
        'Item you want to know the start/end dates
        'So select it before run the macro (i.e. ABC from Task)
        selected = ActiveCell.Value
        'Change the Range as you will
        Range("B1").Select
        Do While ActiveCell.Value <> Empty
        If (ActiveCell.Offset(0, 1).Value = selected) Then
            If ActiveCell.Value < startDate Then startDate = ActiveCell.Value
            If ActiveCell.Value > endDate Then endDate = ActiveCell.Value
        Else
        End If
        ActiveCell.Offset(1, 0).Select
        Loop
        If startDate = endDate Then
        MsgBox "For: " & selected & Chr$(13) & "Start date: " & startDate & Chr$(13) & "Unknown End date/Same Dates"
        Else
        MsgBox "For: " & selected & Chr$(13) & "Start date: " & startDate & Chr$(13) & "End Date: " & endDate
        End If
    End Sub