【问题标题】:VBA Excel - Count Rows That Contain a Certain DateVBA Excel - 计算包含特定日期的行
【发布时间】:2020-11-01 13:53:04
【问题描述】:

我正在努力想出正确的逻辑:

工作表 1

 A   |     B
------------------ 
test | 01/01/2020
test | 01/01/2020
test | 02/01/2020
test | 03/01/2020

所以我要做的是遍历 B 列日期,然后计算该日期存在多少行。它会打印出类似的东西

工作表2:

 A   |     B
------------------ 
01/01/2020 | 2
02/01/2020 | 1
03/01/2020 | 1

我在想 A 列是否需要将每个日期绑定到字典然后进行计数?使用 VBA 最有效的方法是什么

【问题讨论】:

  • 不需要 VBA。只需使用数据透视表。而且,如果这对您有用,您可以录制一个宏来设置它。或者您可以使用 Power Query。
  • 我同意@RonRosenfeld。这不需要 VBA。 Pivottable 可以轻松实现您想要的。

标签: excel vba


【解决方案1】:

带计数的唯一字典

  • 通过以下方式使用字典,可以在写入的同时,将每个键(Key)的计数写入其值(.item(Key))

守则

Option Explicit

Sub writeUniqueCount()
    
    ' Define Source Column Range.
    Dim rng As Range
    Set rng = ThisWorkbook.Worksheets("Sheet1").Range("A1:A10")
    ' Write Source Column Range to Data Array.
    Dim Data As Variant
    Data = rng.Value
    With CreateObject("Scripting.Dictionary")
        ' Write unique values from Data Array to Unique Dictionary.
        Dim Key As Variant
        Dim i As Long
        For i = 1 To UBound(Data, 1)
            Key = Data(i, 1)
            If Not IsError(Key) And Not IsEmpty(Key) Then
                .Item(Key) = .Item(Key) + 1 ' Count!
            End If
        Next i
        ' Validate Unique Dictionary.
        If .Count = 0 Then
            Exit Sub
        End If
        ' Write values from Unique Dictionary to two-column Data Array:
        ' first column are the keys, second column is the count of each key.
        ReDim Data(1 To .Count, 1 To 2)
        i = 0
        For Each Key In .keys
            i = i + 1
            Data(i, 1) = Key
            Data(i, 2) = .Item(Key)
        Next Key
    End With
    ' Write values from two-column Data Array to two-column Target Range.
    With ThisWorkbook.Worksheets("Sheet1").Range("B1")
        Set rng = .Resize(UBound(Data, 1), 2)
    End With
    rng.Value = Data
    
End Sub

【讨论】:

  • 这很好用,这是我自己想不到的——数据透视表似乎更容易工作......但是,我需要这个解决方案。感谢您抽出宝贵时间!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-25
  • 1970-01-01
  • 1970-01-01
  • 2021-08-06
  • 2015-01-10
相关资源
最近更新 更多