|
仅供参考
- Sub test()
- Dim conn As Object, sql$, Sh As Worksheet, i As Integer, r As Long
- Set Sh = Sheets("Sheet2")
- Set conn = CreateObject("adodb.connection")
- If Val(Application.Version) < 12 Then
- 'You use Excel 2000-2003
- FileExtStr = ".xls": FileFormatNum = -4143
- conn.Open "provider=microsoft.jet.oledb.4.0;extended properties='excel 8.0;hdr=yes;';Data Source=" & ThisWorkbook.FullName
- Else
- 'You use Excel 2007-2010
- FileExtStr = ".xlsx": FileFormatNum = 51
- conn.Open "provider=Microsoft.ACE.OLEDB.12.0;extended properties='excel 12.0;hdr=yes';data source=" & ThisWorkbook.FullName
- End If
- sql = "Select A1,A2,A3,A4,sum(期初),sum(入库), sum(出库),SUM(期初)+SUM(入库)+SUM(出库) AS 库存 from (" & _
- "select 物品代码 as A1,物品名称 AS A2,规格型号 AS A3,单位 AS A4,0 as 期初,sum(数量) as 入库,0 as 出库 from [Sheet1$] where 票据类型='入库' group by 物品代码,物品名称,规格型号,单位 " & _
- "UNION ALL " & _
- "select 物品代码 AS A1,物品名称 AS A2,规格型号 AS A3,单位 AS A4,0 as 期初,0 as 入库,sum(数量) as 出库 from [Sheet1$] where 票据类型='出库' group by 物品代码,物品名称,规格型号,单位 " & _
- ") group by A1,A2,A3,A4 order by A1,A2,A3"
- Sh.Range("A2").CopyFromRecordset conn.Execute(sql)
- conn.Close
- Set conn = Nothing
- r = Sh.Cells(Sh.Rows.Count, 1).End(xlUp).Row 'A栏最后非空白列
- Sh.Cells(r + 1, 1) = "合计"
- For i = 5 To 8
- Sh.Cells(r + 1, i) = Application.WorksheetFunction.Sum(Sh.Range(Sh.Cells(2, i), Sh.Cells(r, i))) '加总合计
- Next i
- MsgBox "OK"
- End Sub
复制代码 |
|