首页 > Excel专区 > Excel教程 >

excel 实现更为普遍的二维报表整理为数据清单的方法

Excel教程 2021-10-12 10:25:03

下面1图所示的二维报表数据。这种表格设计的初衷是为了方便输入数据,但是却为数据汇总和分析造成了麻烦。例如,要统计办公室的复印纸的耗量和费用,就比较麻烦。对于这样的表格,最后将其设计为日记流水账的形式,如图2所示。尽管在输入数据时有些麻烦,但统计汇总分析就很方便。

  那么如何将图1所示的二维表格转换为图2所示的规范表格呢,利用函数也是很复杂的,可以利用VBA编制程序比较方便。下面就是相关的VBA程序代码。

Public Sub DataList()
    Dim myArray As Variant
    Dim n As Long, i As Long, k As Long, j As Long
    Dim ws0 As Worksheet
    Dim wsNew As Worksheet
    myArray = Array("日期", "材料", "单位", "部门", "数量", "金额")
    Set ws0 = Worksheets("不科学表格")
    n = ws0.Range("A65536").End(xlUp).Row - 2
    On Error Resume Next
    Application.DisplayAlerts = False
    Worksheets("数据清单").Delete
    Application.DisplayAlerts = False
    On Error GoTo 0
    Set wsNew = Worksheets.Add
    With wsNew
        .Name = "数据清单"
        .Range("A1:F1") = myArray
        k = 1
        For j = 4 To 8 Step 2
            For i = 1 To n
                If ws0.Cells(i + 2, j) <> "" Then
                    .Cells(k + 1, 1) = Format(ws0.Cells(i + 2, 1), "yyyy-m-d")
                    .Cells(k + 1, 2) = ws0.Cells(i + 2, 2)
                    .Cells(k + 1, 3) = ws0.Cells(i + 2, 3)
                    .Cells(k + 1, 4) = ws0.Cells(1, j)
                    .Cells(k + 1, 5) = ws0.Cells(i + 2, j)
                    .Cells(k + 1, 6) = ws0.Cells(i + 2, j + 1)
                    k = k + 1
                End If
            Next i
        Next j
    End With
    Set ws0 = Nothing
    Set wsNew = Nothing
End Sub

  只要运行上面代码,就可以迅速的将二维报表数据转换为数据清单。现在就可以利用整理好的“数据清单”制作数据透视表。

数据透视表系列教程十


标签: excel实现更为普遍二维报表整理

office教程网 Copyright © 2016-2020 https://www.office9.cn. Some Rights Reserved.