返回列表 上一主題 發帖

[發問] 2條件下做資料整理相加

本帖最後由 singo1232001 於 2023-3-1 09:05 編輯

回復 1# willeddie


    Sub TEST()
Set cn = CreateObject("adodb.connection")
C = ".0; Data Source=" & ThisWorkbook.FullName
Select Case Application.Version
Case Is < 12: cn.Open "Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties=Excel 8" & C
Case Else: cn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Extended Properties=Excel 12" & C: End Select

q = "select 日期,產品,sum(數量) as 數量 from [工作表2$a1:C] "
q = q & "group by 日期,產品  having 日期 is not null "

With Sheets("工作表2"): .Range("F:H").ClearContents
Set rs = cn.Execute(q)
For i = 0 To rs.Fields.Count - 1 '取標題,如果不要可省略
    .Cells(1, i + 6) = rs.Fields(i).Name
Next
.Cells(2, 6).CopyFromRecordset rs : End With
End Sub

分組查詢sql.zip (18.23 KB)

TOP

本帖最後由 singo1232001 於 2023-3-1 09:33 編輯

回復 9# singo1232001

Sub TEST()
Select Case Application.Version
Case Is < 12: B = "Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties=Excel 8"
Case Else: B = "Provider=Microsoft.ACE.OLEDB.12.0;Extended Properties=Excel 12": End Select
Set cn = CreateObject("adodb.connection")
cn.Open B & ".0; Data Source=" & ThisWorkbook.FullName
q = "select 日期,產品,sum(數量)from[工作表2$a1:C]group by 日期,產品 having 日期 is not null"
Set rs = cn.Execute(q)
[F:H].ClearContents: [F1:H1] = [A1:C1].Value
[F2].CopyFromRecordset rs
End Sub

分組查詢sql v2 努力縮減.zip (18.15 KB)

TOP

本帖最後由 singo1232001 於 2023-3-1 10:14 編輯

回復 10# singo1232001

'很硬要的縮到極限
Sub TEST()
Set CN = CreateObject("adodb.connection"): V = Application.Version: [F:H].ClearContents
If V >= 12 Then V = "Provider=Microsoft.ACE.OLEDB.12.0;Extended Properties=Excel 12.0; "
If V < 12 Then V = "Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties=Excel 8.0; "
CN.Open V & "Data Source=" & ThisWorkbook.FullName
q = "select 日期,產品,sum(數量)from[工作表2$a1:C]group by 日期,產品 having 日期 is not null"
Set RS = CN.Execute(q): [F1:H1] = [A1:C1].Value: [F2].CopyFromRecordset RS
End Sub

TOP

        靜思自在 : 【行善要及時】行善要及時,功德要持續。如燒開水一般,未燒開之前千萬不要停熄火候,否則重來就太費事了。
返回列表 上一主題