簡體   English   中英

Excel VBA宏可根據日期計算特定單詞出現的次數(該日期將轉換為星期數)

[英]Excel VBA macro to count the number of times a specific word appears according to a date (that would be converted to week number)

因此,我在下面顯示了A列(包含單詞)和C列(包含日期)。 這些列有時會被新的標題分隔,例如“ Word”和“ Date”以及空白。

Word               Date
BV                 12/06/2017
BV                 12/06/2017
BV                 13/06/2017
BV                 13/06/2017
BR                 17/07/2017
BR                 17/07/2017
BR                 24/07/2017

Word               Date
BT                 30/07/2017
BT                 30/07/2017

Word               Date
BY                 05/08/2017

首先,日期將按照星期數轉換為新的列D,例如12/06/2017至第24周。

使用類似:

Sub TimeConverter()    
  Dim I as Long, MaxRow as Long
  MaxRow = Range("A" & Rows.count).End(xlUp).Row
  For I = 2 to MaxRow
    Cells(I, "D").Value = DatePart("ww", Cells(I, "C"), 7)
  Next 
End Sub

然后,我希望VBA宏代碼遍歷A列,查找單詞出現的次數,並將與同一周編號上的日期匹配的次數匹配到新的B列中。

使用類似:

=COUNTIF(A:A, "BV")
=COUNTIF(A:A, "BR")

Output
# 4
# 3

現在將它們組合在一起,以便可以將唯一的單詞(A列)計數(B列)分離為相應的星期數(D列)。

所需輸出:

BV      4      24
BR      2      29
BR      1      30
BT      2      30
BY      1      31

任何建議都很好! 謝謝。

假設使用您的VBA代碼,您已經成功獲得了以下內容作為輸入:

在此處輸入圖片說明

然后,如注釋中所述, 您需要實現一個字典來獲得如下內容:

在此處輸入圖片說明

如您所見,詞典的鍵是單詞+周號。 因此, BR29BR30不同。

復制樣本輸入,運行下面的代碼,您將獲得所需的輸出:

Option Explicit

Public Sub TestMe()

    Dim myDict          As Object
    Dim lngCounter      As Long
    Dim strKey          As String
    Dim objKey          As Object

    Set myDict = CreateObject("Scripting.Dictionary")

    For lngCounter = 1 To 14
        strKey = Cells(lngCounter, 1) & Cells(lngCounter, 3)
        If myDict.exists(strKey) Then
            myDict(strKey) = myDict(strKey) + 1
        Else
            myDict(strKey) = 1
        End If
    Next lngCounter

    For lngCounter = 0 To myDict.Count - 1
        Cells(lngCounter + 1, 6) = myDict.Items()(lngCounter)
        Cells(lngCounter + 1, 7) = myDict.keys()(lngCounter)
    Next lngCounter

End Sub

然后,您需要做更多的工作才能找到一種將密鑰從BV24拆分為BV和24的方法。您還需要找到一種從結果中消除零的方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM