在 Excel 2013 中根据闰年将单列数据拆分为多列

在 Excel 2013 中根据闰年将单列数据拆分为多列

我有大约 100 个包含天气数据的 MS Excel 文件。

我需要按年计算的数据,但文件只有一列,包含大约 140 年的数据,手动复制粘贴非常耗时。那么,有没有办法使用简单的命令来拆分数据,这些命令可以拖动,以便将 1 年(365 个单元格)的数据复制到连续的行中。

另外,还有闰年问题,即每3年之后的数据应该是366个单元格,而不是剩下的365个单元格。

答案1

因为你似乎无法让其他宏正常工作这个问题,我想我会根据您在这里提供的确凿事实来让您轻松理解。

对于您特定的日期范围,此宏将起作用 -

Sub test()
'fill dates
Application.ScreenUpdating = False
Dim NumCells As Integer
NumCells = [counta(A:A)]
Columns("A:A").Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove

Cells(1, 1) = "1/1/61"
Range(Cells(1, 1), Cells(NumCells, 1)).DataSeries

'move data
Dim c As Range
Dim cCol As Integer
cCol = 4
label:
For Each c In Range("A:A")
If c.Value = "" Then Exit Sub

    For i = 1 To 366
        If Not Right(c, 4) = Right(c.Offset(i), 4) Then
         GoTo label2
        End If
    Next
label2:
        Range(c, c.Offset(i - 1, 1)).Copy
        Cells(1, cCol).PasteSpecial Paste:=xlPasteValues
        Range(c, c.Offset(i - 1, 1)).Delete xlShiftUp
        Range(Cells(1, cCol), Cells(366, cCol)).NumberFormat = "mm/dd/yyyy"
        cCol = cCol + 3
        GoTo label

Next
Application.ScreenUpdating = True
End Sub

答案2

尝试这个宏

Sub Button1_Click()

Dim row As Integer
row = 1

Dim otherRow As Integer
otherRow = 1

Dim year As Integer
year = 1

Dim column As Integer
column = 66 ' start on B

Dim preColumn As Integer
preColumn = 64

Do While (True)

If Range("A" & row).Value = "" Then
    Exit Do
End If

If (column > 90) Then
    preColumn = preColumn + 1
    column = 65
End If


If (preColumn = 64) Then

Range(Chr(column) & otherRow).Value = Range("A" & row).Value

Else

Range(Chr(preColumn) & Chr(column) & otherRow).Value = Range("A" & row).Value

End If


Dim addition As Integer
addition = 0

If (year = 4) Then
    addition = 1
End If

If (otherRow = 365 + addition) Then
column = column + 1
otherRow = 0

year = year + 1

End If


If (year > 4) Then
 year = 1
End If

row = row + 1
otherRow = otherRow + 1

Loop

End Sub

相当无用的运行屏幕截图:

在此处输入图片描述

在此处输入图片描述

请在您的数据副本上尝试一下...我不会对破坏一切负责。您还需要正确测试并确保所有数据都存在,但我认为这没问题。

相关内容