如何使用VBA脚本在excel中过滤唯一名称并显示唯一名称的行数据?

时间:2019-10-12 20:19:36

标签: excel vba

我想创建可以捕获唯一名称并显示唯一名称的行数据的VBA脚本。

例如:

Names       Time      Cases 
 Tony       06:14:43   54
 Peter      06:04:43   54
 Tony       06:15:43   54
 Tony       06:16:43   54
 Peter      06:12:43   54
 Tony       06:21:43   54
 Tony       06:33:43   54
 Tony       06:45:43   54
 Peter      06:14:43   54
 Peter      06:21:43   54
 Peter      06:22:43   54
 Tony       06:47:43   54
 Peter      06:33:43   54
 Peter      06:59:43   54

我想找到用户Tony并显示他的工作时间开始时间和结束时间,并显示Tony做过多少案例。 与彼得一样。

你能告诉我吗?

我尝试过这样的事情:

Sub test()

    Dim values As Variant
    values = Sheet1.Range("AL3:AL600").Value2 

    'Add a reference to Microsoft Scripting Runtime
    Dim dic As Scripting.Dictionary
    Set dic = New Scripting.Dictionary

    'Set the comparison mode to case-sensitive
    dic.CompareMode = BinaryCompare

    Dim valCounter As Long
    For valCounter = LBound(values) To UBound(values)
        'Check if the name is already in the dictionary
        If Not dic.Exists(values(valCounter, 1)) Then
            'Add the new name as a key, along with a dummy value of 0
            dic.Add values(valCounter, 1), 0
        End If
    Next valCounter

    'Extract the dictionary's keys as a 1D array
    Dim result As Variant
    result = dic.Keys

    Worksheets.Add

    Range("A3:A20").Value = result

End Sub

我可以获得唯一的名称,但是我不知道如何提取唯一名称的行数据。

1 个答案:

答案 0 :(得分:0)

遵循这些思路可能会有所帮助

Sub testing()

Dim arrTemp() As Variant
Dim lngCount As Long
Dim lngLoop As Long

arrTemp = getTimes("Tony", ActiveSheet.Range("A2:b15"))

lngCount = UBound(arrTemp)

For lngLoop = 0 To lngCount
    Range("g1").Offset(lngLoop, 0).Value = arrTemp(lngLoop)
Next lngLoop

Erase arrTemp

End Sub

Function getTimes(strLookFor As String, _
                    rngLookAt As Excel.Range, _
                    Optional lngColumnForTimeOffset As Long = 1) As Variant()

Dim rngInspect As Excel.Range
Dim dicAnalysis As New Scripting.Dictionary



For Each rngInspect In rngLookAt.Columns(1).Cells

    If rngInspect = strLookFor Then
        dicAnalysis.Add CStr(dicAnalysis.Count), _
                        CDate(rngInspect.Offset(0, lngColumnForTimeOffset).Text)
    End If

Next rngInspect

getTimes = dicAnalysis.Items()

End Function