Excel 2010 VBA 入门 083 数据处理之按单列汇总数据

2021/5/4 10:57:52

本文主要是介绍Excel 2010 VBA 入门 083 数据处理之按单列汇总数据,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

目录

示例

数据表

汇总表

代码


示例

如图所示,该表为某公司的销售数据。如何使用VBA按商品名汇总销售数量和收入?

数据表

日期商品代码商品名数量收入
2011/8/1701.0032ASWDVBN0.054273.5
2011/1/2801.0003ERTGH13589.74
2011/1/2901.0003ERTGH13846.15
2011/2/101.0004EFGTYUI113247.86
2011/2/201.0004EFGTYUI116239.32
2011/2/501.0007DFRTYHB11282.05
2011/1/2701.0003ERTGH311025.64
2011/4/2601.0012ZXSC3569.23
2011/4/2501.0011RGHUO871794.87
2011/4/2401.0011RGHUO1085470.09
2011/4/2801.0014ASCERT2511965.81
2011/5/2101.0014ASCERT2511858.97
2011/9/1101.0014ASCERT2511858.97
2011/2/301.0005WERDS40153846.2
2011/8/401.0028VGRYUI40102564.1
2011/10/1801.0014ASCERT5023717.95
2011/7/901.0014ASCERT5023717.95
2011/1/3101.0003ERTGH60256410.3
2011/1/3001.0003ERTGH74316239.3
2011/6/2501.0014ASCERT7535576.92
2011/2/1101.0007DFRTYHB100108547
2011/2/1201.0007DFRTYHB100109401.7
2011/2/2301.0007DFRTYHB100104273.5
2011/6/601.0014ASCERT10047435.9
2011/10/1501.0014ASCERT10047435.9
2011/10/1901.0014ASCERT10047435.9
2011/6/2401.0014ASCERT10047435.9
2011/6/3001.0014ASCERT10048290.59
2011/11/501.0014ASCERT15071153.85
2011/8/1501.0032ASWDVBN150620897.4
2011/8/1601.0032ASWDVBN150620897.4

汇总表

商品名数量合计收入合计
ASWDVBN300.051246068
ERTGH139591111.1
EFGTYUI229487.18
DFRTYHB1710118078205
ZXSC3569.23
RGHUO18157265
ASCERT3565016947158
WERDS40153846.2

代码

Option Explicit

Sub 按单列汇总数据()
    Dim shtData As Worksheet
    Dim shtSum As Worksheet
    Dim rowSum As Long
    Dim rowData As Long
    Dim Rng As Range
    Dim sKey As String
    
    Set shtData = Sheets("sheet1")
    Set shtSum = Sheets("sheet2")
    
    rowSum = 2
    shtSum.Range("A2:C" & Rows.Count).Clear
    
    '获取汇总列字段不重复记录
    For rowData = 2 To shtData.Range("A1").CurrentRegion.Rows.Count
        sKey = shtData.Cells(rowData, "C").Value
        Set Rng = shtSum.Range("A:A").Find(sKey, lookat:=xlWhole)
        If Rng Is Nothing Then
            shtSum.Cells(rowSum, "A").Value = sKey
            rowSum = rowSum + 1
        End If
    Next rowData
    
    '汇总
    For rowSum = 2 To shtSum.Range("A1").CurrentRegion.Rows.Count
        sKey = shtSum.Cells(rowSum, "A").Value
        For rowData = 2 To shtData.Range("A1").CurrentRegion.Rows.Count
            If shtData.Cells(rowData, "C").Value = sKey Then
                shtSum.Cells(rowSum, "B").Value = shtSum.Cells(rowSum, "B").Value + shtData.Cells(rowData, "D").Value
                shtSum.Cells(rowSum, "C").Value = shtSum.Cells(rowSum, "C").Value + shtData.Cells(rowData, "E").Value
            End If
        Next rowData
    Next rowSum
End Sub

 



这篇关于Excel 2010 VBA 入门 083 数据处理之按单列汇总数据的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程