我学VBA:获取物料代码的唯一值


  要求:根据发货单的物料清单,进行发出材料的分类汇总,首先按物料代码获取物料的唯一值,再进行分类汇总。

  代码:

  Sub 分类汇总()

  ' 唯一值提取

  Dim N As Integer

  N = [A65536].End(xlUp).Row

  Dim Shtfl As Worksheet

  Set Shtfl = Worksheets("出库单分类汇总")

  Shtfl.Range("a1") = "物料代码"

  Range("C2:C" & N).AdvancedFilter Action:=xlFilterCopy, CopyToRange:=Shtfl.Range("A2"), Unique:=True

  '引用数据

  Dim N2 As Integer

  N2 = Shtfl.Range("A65536").End(xlUp).Row

  For N4 = 2 To N2 Step 1

      For N3 = 2 To N Step 1

          If Shtfl.Cells(N4, 1) = Cells(N3, 3) Then

  : Rem 如果物料代码相同

              Shtfl.Cells(N4, 2) = Cells(N3, 4) '类别

              Shtfl.Cells(N4, 3) = Cells(N3, 5) '物料名称

              Shtfl.Cells(N4, 4) = Cells(N3, 6) '物料规格

              Shtfl.Cells(N4, 5) = Cells(N3, 7) '单位

                  Sum = Sum + Cells(N3, 8) '累计数量

                  SUM2 = SUM2 + Cells(N3, 10) '累计金额

              Shtfl.Cells(N4, 6) = Sum '数量

              Shtfl.Cells(N4, 8) = SUM2 '金额

              Shtfl.Cells(N4, 7) = Shtfl.Cells(N4, 8) / Shtfl.Cells(N4, 6) '计算单价

          End If

      Next

      Sum = 0

      SUM2 = 0

  Next

  MsgBox "出库单的领料汇总表已编制完成!请检查!", 64, "飞扬财务:专注于财务领域的应用与培训!"

  End Sub