2016-07-31 29 views
0

我試圖將總天數的總和粘貼到當前月份。查找本月並貼上它的總和

這是我迄今爲止,但它不會根據當月總的容器列粘貼

enter image description here

這是我的代碼

Sub Macro1() 
    ' 
    ' Macro1 Macro 
    ' 
    For i = 2 To 13 
     If Cells(i, 5) = Month Then Cells(i, 6) = Cells(34, 2) 
     Cells(i, 6).Select 
     Selection.copy 
     Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _ 
     :=False, Transpose:=False 
     Application.CutCopyMode = False 
    Next i 
End Sub 
+0

是否有一個原因,[SUMIFS函數(https://support.office.com/en-us/article/SUMIFS-function-C9E748F5-7EA7-455D-9406-611CEBCE642B)獲不工作? – Jeeped

+0

我是VBA的初學者,不知道它是如何工作的 –

+0

爲什麼不是一個數據透視表山姆? –

回答

0

你可以使用這樣的腳本字典:

Sub SumContainersByMonth() 
    Dim c As Range, DataRange As Range 
    Dim count As Double 
    Dim key As String 
    Dim k, Keys, Items 
    Dim dict As Object 

    Set dict = CreateObject("Scripting.Dictionary") 

    Set DataRange = Range("A2", Range("A1").End(xlDown)) 

    For Each c In DataRange 
     key = DateSerial(Year(c), Month(c), 1) 
     count = c.Offset(0, 1) + dict(key) 
     dict(key) = count 
    Next 

    Keys = dict.Keys 
    Items = dict.Items 

    Range("E2").Resize(UBound(Keys) + 1) = WorksheetFunction.Transpose(Keys) 
    Range("F2").Resize(UBound(Items) + 1) = WorksheetFunction.Transpose(Items) 

End Sub 

我會對您的項目設置進行一些更改並對數據進行小計。

以下是方法

我會在Day的左邊插入一個Month-Year列。 Month-Year的值應該等於Day列的值,但其格式應該是MMM-YY。

enter image description here

在數據選項卡上單擊分類彙總。

enter image description here

下面的圖片應用設置。

enter image description here

到行號左側單擊,,或選擇如何顯示您的數據。

enter image description here

+0

謝謝,我會嘗試它 –