Excel:根据最小/最大值搜索和删除列

qhhrdooz  于 2022-11-18  发布在  其他
关注(0)|答案(1)|浏览(99)

我有一个很大的表,上面有物品的输入和输出时间。我想把周期时间用图形表示出来。

红色框中是物品的序列号。黄色框中是开始时间,绿色框中是结束时间。序列号不一定总是3个相同,但也可以完全不同(例如,6个相同的序列号)。
要显示周期时间,我需要一个序列号中黄色框中的最早开始时间(最小值)和绿色框中的最大值作为结束时间(最大值)。
这是不可能的手动,因为工作表太大了。有人有一个想法与实现?问题不是要找到最小的黄色框和最大的绿色框,而是公式,以搜索通过列后,相同的序列号。

7rtdyuoh

7rtdyuoh1#

请测试下一个解决方案/代码。由于您没有回答澄清问题,因此假定显示的列为“A:D”,列“B:D”中的时间格式为Date"hh:mm:ss")。代码使用字典来保存唯一的序列号,并计算/存储第二列的最小值和第四列的最大值。序列号可以以任何顺序出现

Sub ExtractMinMaxDates()
   Dim sh As Worksheet, lastR As Long, i As Long, arr, arrEl, arrFin
   Dim key As Variant, dict As Object
   
   Set sh = ActiveSheet 'use here the necessary sheet
   lastR = sh.Range("A" & sh.rows.count).End(xlUp).row 'last row
   
   arr = sh.Range("A2:D" & lastR).Value2 'place the range in an array for faster iteration/processing
   
   Set dict = CreateObject("Scripting.Dictionary") 'set the necessary dictionary
   For i = 1 To UBound(arr)    'iterate between the array rows
        If Not dict.Exists(arr(i, 1)) Then 'if a dictionary key has not been created:
            dict.Add arr(i, 1), Array(arr(i, 2), arr(i, 4)) 'make it and place (as item) an array containing
        Else                                                'time from columns 2 and 4
            arrEl = dict(arr(i, 1))                         'place the item in an array
            If arr(i, 2) < arrEl(0) Then arrEl(0) = arr(i, 2) 'keep the minimum
            If arr(i, 4) > arrEl(1) Then arrEl(1) = arr(i, 4) 'keep the maximum
        End If
   Next i
   'Redim the final array to keep the dictionary data:
   ReDim arrFin(1 To dict.count, 1 To 3): i = 1

   'fill the final aray with the necesssary data
   For Each key In dict.Keys
        arrFin(i, 1) = key: arrFin(i, 2) = dict(key)(0)
        arrFin(i, 3) = dict(key)(1): i = i + 1
   Next
   
   'Drop the array content at once anf format the necessary columns:
   With sh.Range("F2").Resize(dict.count, 3) 'it may return anywhere (just change "F2" with needed cell)
        .Value2 = arrFin
        .Columns(2).EntireColumn.NumberFormat = "hh:mm:ss"
        .Columns(3).EntireColumn.NumberFormat = "hh:mm:ss"
  End With
End Sub

请在测试后发送一些反馈。

相关问题