Excel VBA:每行分隔为新行的单行日期

时间:2014-03-10 16:11:19

标签: excel vba

我有一列日期(范围从1月到12月),我已将其转换为一行。

我想将这一行日期(按月)分成新行(每月一行)。

如果可能,我想在原始行所在的同一工作表中执行此操作。 原始数据列是(C2:C54)已转置到(D4:BD4)。 希望按月分隔的新行在D5上开始。

我没有在网上找到任何将数据保存在同一工作表中并在新行中按月分隔的内容。希望在这里找到帮助。感谢所有的帮助,我提前感谢你。

1 个答案:

答案 0 :(得分:0)

如果我正确地理解了这个问题,这个VBA会为你完成这个工作:

Sub Dt_Trans()
  'I is a numeric value that will offset each picked up date 
  'by 1 column, and is reset when a new month is picked up
  Mprev = Month(Range("D4"))
  'Loop through each cell in the range
  For Each C In Range("D4:BD4").Cells
     'If we reach a new month, set the I value back to zero 
     'so the new row starts from column D again
     If Month(C) <> Mprev Then
     I = 0
     End If
     'Offset D4 by the the month value to move down rows
     'I value to move across columns
     Range("D4").Offset(Month(C), I) = C.Value
     'Iterate I to avoid overwriting
     I = I + 1
     'Set Mprev so Month can be compared for the next cell
     Mprev = Month(C)
  Next
End Sub