汇总表的完整代码,请替换代码并测试
- Private Sub Worksheet_Change(ByVal Target As Range)
- Dim rs As New ADODB.Recordset, SQL$, i%
- If Target.Address = "$E$2" Then
- SQL = "select 物料编码,期初数量 as a,期初金额 as b,0 as c,0 as d,0 as e,0 as f from [物品表$] "
- SQL = SQL & " Union All Select 物料编码,入库数量-出库数量,入库金额-出库金额,0,0,0,0 from [DataBase$] where 月<" & Target.Value
- SQL = SQL & " Union All Select 物料编码,0,0,入库数量,入库金额,出库数量,出库金额 from [DataBase$] where 月=" & Target.Value
- SQL = "Select 物料编码,sum(a) as 期初数量,val(format(sum(b)/sum(a),'0.00')) as 期初单价,sum(b) as 期初金额," & _
- "sum(c) as 入库数量,val(format(sum(d)/sum(c),'0.00')) as 入库单价,sum(d) as 入库金额," & _
- "sum(e) as 出库数量,val(format(sum(f)/sum(e),'0.00')) as 出库单价,sum(f) as 出库金额," & _
- "(sum(a)+sum(c)-sum(e)) as 期末数量," & _
- "val(format((sum(b)+sum(d)-sum(f))/(sum(a)+sum(c)-sum(e)),'0.00')) as 期末单价," & _
- "(sum(b)+sum(d)-sum(f)) as 期末金额 from (" & SQL & ") Group by 物料编码"
- SQL = "Select a.物料编码,物料名称,规格,单位,期初数量,期初单价,期初金额,入库数量,入库单价,入库金额," & _
- "出库数量,出库单价,出库金额,期末数量,期末单价,期末金额 " & _
- "from [物品表$] a Left Join (" & SQL & ") b on a.物料编码=b.物料编码"
- rs.Open SQL, cnn, 1, 3
- Range("A5:Z65536").ClearContents
- Range("A5:Z65536").Borders.LineStyle = xlNone
- Range("A5").CopyFromRecordset rs
-
-
- If rs.RecordCount > 0 Then
- i = rs.RecordCount
- With Range("A5").Offset(i, 1)
- .Value = "合计"
- .Offset(0, 5).FormulaR1C1 = "=SUM(R5C:R" & i + 4 & "C7)"
- .Offset(0, 8).FormulaR1C1 = "=SUM(R5C:R" & i + 4 & "C)"
- .Offset(0, 11).FormulaR1C1 = "=SUM(R5C:R" & i + 4 & "C)"
- .Offset(0, 14).FormulaR1C1 = "=SUM(R5C:R" & i + 4 & "C)"
- End With
- With Range("A5").Resize(i + 1, 16)
- .Borders.LineStyle = xlContinuous
- .Font.Size = 10 '字号,根据需要修改
- End With
- End If
- rs.Close
- End If
- Set rs = Nothing
- End Sub
复制代码 |