返回列表 上一主題 發帖

請教各位前輩vba 關於單一儲存格式內統計問題~

本帖最後由 stillfish00 於 2014-5-26 19:59 編輯

回復 1# ii31sakura
僅供參考
最好的做法還是一開始的表格就先定義明確,單一儲存格不要多用途。
  1. Sub Test()
  2.   Dim d, i As Long, dteDate As Date, lValue As Long, sType As String
  3.   Dim oReg, oMatch, x, y, lCnt As Long, ar
  4.   
  5.   Set d = CreateObject("scripting.dictionary")
  6.   Set oReg = CreateObject("vbscript.regexp")
  7.   With oReg
  8.     .Global = True
  9.     .Pattern = "(\d+)-(\S+)"
  10.   End With
  11.   
  12.   'Analyze
  13.   With Sheets("Sheet1").[A1].CurrentRegion
  14.     If .Rows.Count < 2 Then Exit Sub
  15.     For i = 2 To .Rows.Count
  16.       dteDate = .Cells(i, 1).Value
  17.       'make 2 levels dictionary
  18.       If Not d.exists(dteDate) Then Set d(dteDate) = CreateObject("scripting.dictionary")
  19.       
  20.       Set oMatch = oReg.Execute(.Cells(i, 2).Value)
  21.       For Each x In oMatch
  22.         lValue = CLng(oReg.Replace(x.Value, "$1"))
  23.         sType = oReg.Replace(x.Value, "$2")
  24.         With d(dteDate)
  25.           If .exists(sType) Then
  26.             .Item(sType) = .Item(sType) + lValue
  27.           Else
  28.             .Item(sType) = lValue
  29.             lCnt = lCnt + 1
  30.           End If
  31.         End With
  32.       Next
  33.     Next
  34.   End With
  35.   
  36.   'Read to array
  37.   ReDim ar(1 To lCnt, 1 To 3)
  38.   i = 0
  39.   For Each x In d.keys
  40.     For Each y In d(x).keys
  41.       i = i + 1
  42.       ar(i, 1) = x
  43.       ar(i, 2) = y
  44.       ar(i, 3) = d(x)(y)
  45.     Next
  46.   Next
  47.   'Fill into worksheet
  48.   With Sheets("Sheet1").[F1]
  49.     .Resize(1, 3).Value = Array("日期", "其它項目", "其它總數量(顆粒數)")
  50.     .Offset(1).Resize(lCnt, 3).Value = ar
  51.   End With
  52. End Sub
複製代碼

TOP

        靜思自在 : 犯錯出懺悔心,才能清淨無煩惱。
返回列表 上一主題