|
[广告] Excel易用宝 - 提升Excel的操作效率 · Excel / WPS表格插件 ★ 免费下载 ★ ★ 使用帮助★
这几天一直在学习数组和字典法,初步掌握了一点点技巧,再也不会象以前那样N个循环嵌套N次再循环了。。。。。。
附件是今天要解决工作上的一个问题时想出来的拆分BOM表的方法,原来的程序是循环再循环,在回家开着车的时候翻来覆去地想应该如何用字典加快计算速度,忽然想到用字典记录成品在BOM中的开始行号,然后再想到同样可以记录结束行号,这样就能快速地找到成品在BOM中的位置,无需整个BOM循环一次来找数据。
也许有更优化的算法吧?但这也算是我的一点所得,希望能对其他朋友有所启发
Private Sub CommandButton1_Click()
t = Timer
Dim iArr_Data(), iArr_BOM(), iArr_Total(), iArr_Group()
Dim iDict_BOM_S As Object, iDict_BOM_E As Object, iDict_Group As Object
ReDim iArr_Total(1 To 2, 1 To 1)
ReDim iArr_Group(1 To 2, 1 To 1)
Set iDict_BOM_S = CreateObject("Scripting.Dictionary")
Set iDict_BOM_E = CreateObject("Scripting.Dictionary")
With Sh_Data
.Range("A2:C12408").Sort Key1:=.Range("A2"), Order1:=xlAscending, Header:=xlYes, Key2:=.Range("B2"), Order1:=xlAscending, Header:=xlYes
iArr_BOM = .Range("A3:C12408")
iArr_Data = .Range("E3:F" & .Range("E65526").End(xlUp).Row)
For i = 1 To UBound(iArr_BOM)
iDict_BOM_E(iArr_BOM(i, 1)) = i
If iDict_BOM_S.Exists(iArr_BOM(i, 1)) Then
Else
iDict_BOM_S(iArr_BOM(i, 1)) = i
End If
Next
Set iDict_Group = CreateObject("Scripting.Dictionary")
For i = 1 To UBound(iArr_Data)
If iDict_Group.Exists(iArr_Data(i, 1)) Then
k = iDict_Group(iArr_Data(i, 1))
iArr_Group(2, k) = iArr_Group(2, k) + iArr_Data(i, 2)
Else
n = n + 1
iDict_Group(iArr_Data(i, 1)) = n
ReDim Preserve iArr_Group(1 To 2, 1 To n)
iArr_Group(1, n) = iArr_Data(i, 1)
iArr_Group(2, n) = iArr_Data(i, 2)
End If
Next
n = 1
For i = 1 To UBound(iArr_Group, 2)
s = iDict_BOM_S(iArr_Group(1, i))
e = iDict_BOM_E(iArr_Group(1, i))
For x = s To e
ReDim Preserve iArr_Total(1 To 2, 1 To n)
iArr_Total(1, n) = iArr_BOM(x, 2)
iArr_Total(2, n) = iArr_Group(2, i) * iArr_BOM(x, 3)
n = n + 1
Next
Next
Set iDict_Group = CreateObject("Scripting.Dictionary")
n = 0
ReDim iArr_Group(1 To 2, 1 To 1)
For i = 1 To UBound(iArr_Total, 2)
If iDict_Group.Exists(iArr_Total(1, i)) Then
k = iDict_Group(iArr_Total(1, i))
iArr_Group(2, k) = iArr_Group(2, k) + iArr_Total(2, i)
Else
n = n + 1
iDict_Group(iArr_Total(1, i)) = n
ReDim Preserve iArr_Group(1 To 2, 1 To n)
iArr_Group(1, n) = iArr_Total(1, i)
iArr_Group(2, n) = iArr_Total(2, i)
End If
Next
.Range("H3:I3").Resize(UBound(iArr_Group, 2)) = Application.Transpose(iArr_Group)
.Range("H2:I" & 2 + UBound(iArr_Group, 2)).Sort Key1:=.Range("H2"), Order1:=xlAscending, Header:=xlYes
End With
MsgBox Timer - t
End Sub
|
|