本帖最后由 hehex 于 2012-11-5 13:08 编辑
WJD1163 发表于 2012-11-5 11:42
如果只保存单条的话,要改那个代码呀?要怎样改呀??
单条件批号自查模块可以参考本贴13楼那个无错的附件内相关代码,是用单元格区域对象写的。
下面这个是用数组和字典对象写的只保留单条件批号的代码。- Sub 自查()
- '数据库表自查程序,如果有相同批号记录就合并数量,并删除重复批号行,
- '只保留第一行批号出现记录,仓位数据无实际意义了。
- Dim ar() As Variant, br() As Variant, d As Object, i%, cr() As Variant, j%, m%
- Sheet4.Activate
- ar = Range("a1").CurrentRegion
- Set d = CreateObject("scripting.dictionary") '定义字典对象
- For i = 2 To UBound(ar)
- If ar(i, 3) <> "" Then d(ar(i, 3)) = d(ar(i, 3)) + ar(i, 4) '单条件批号读入字典,Key: 批号, Item: 该批号对应的所有记录数量和
- Next
- ReDim br(1 To d.Count, 1 To 8)
- ReDim cr(1 To d.Count, 1 To 2)
- cr = WorksheetFunction.Transpose(Array(d.keys, d.items))
-
- For i = 1 To UBound(br)
- 'j = InStr(cr(i, 1), ",")
- br(i, 3) = cr(i, 1) '读入不重复的批号进数组br 第3列
- 'br(i, 5) = Mid(cr(i, 1), j + 1, Len(cr(i, 1)) - j)
- br(i, 4) = cr(i, 2) '将合计数量读入br 第4列
- Next
- For j = 1 To UBound(br)
- For i = 2 To UBound(ar)
- If (br(j, 3) = ar(i, 3)) Then
- br(j, 1) = ar(i, 1)
- br(j, 2) = ar(i, 2)
- br(j, 3) = ar(i, 3)
- br(j, 5) = ar(j, 5)
- br(j, 6) = ar(i, 6)
- br(j, 7) = ar(i, 7)
- br(j, 8) = ar(i, 8)
- End If
- Next
- Next
- Range("a2:h8").ClearContents
- Range("a2").Resize(UBound(br), 8) = br
- Set d = Nothing
- Erase ar: Erase br: Erase cr
- End Sub
复制代码 |