![](/img/trans.png)
[英]Excel VBA: Need to Delete Rows in which Cells contain a Date within 7 days of the current Date
[英]VBA Excel - Count Rows That Contain a Certain Date
我正在努力為此提出正確的邏輯:
工作表 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 執行此操作的最有效方法是什么
編碼
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.