|
楼主 |
发表于 2024-6-12 03:30
|
显示全部楼层
[广告] Excel易用宝 - 提升Excel的操作效率 · Excel / WPS表格插件 ★ 免费下载 ★ ★ 使用帮助★
谢谢你的思路,但没有使用好,目标没有实现实现。
采用循环法,是目标需求结果,但运行时间太长。需要进一步优化。
- Function SqlRetuRs(Str)
- Dim Cn As ADODB.Connection
- Set Cn = New ADODB.Connection
- Dim Rs As ADODB.Recordset
- Set Rs = New ADODB.Recordset
-
- '
- If InStr(UCase(Application.Path), "WPS") > 0 Then
- Cn.Open "Provider=Microsoft.JET.OLEDB.4.0;Extended Properties='Excel 8.0;HDR=yes';Data Source=" & ThisWorkbook.FullName
- Else
- Cn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Extended Properties='Excel 12.0;HDR=yes';data source=" & ThisWorkbook.FullName
- End If
- Rs.Open Str, Cn, adOpenKeyset, adLockOptimistic
- Set SqlRetuRs = Rs
- End Function
- '''
- Sub ll2()
- Dim Str
- Dim Rng As Range, oRng As Range
- Set Rng = Selection
- Dim Sht As Worksheet
- Set Sht = Rng.Parent
- Set Rng = Sht.Range(Sht.Cells(7, 1).Formula)
- Rng.Clear
- Set Rng = Sht.Range(Sht.Cells(6, 1).Formula)
- Debug.Print Rng.Address
- Str = "Select Distinct oDate,Name,Count(Name) "
- Str = Str & "From [Sheet1$J13:L54] "
- Str = Str & "Where Not Name is Null Group by oDate,Name"
- Debug.Print Str
- Dim Rs As ADODB.Recordset, Rs1 As ADODB.Recordset
- Set Rs = SqlRetuRs(Str)
- Sht.Cells(15, 1).CopyFromRecordset Rs
- '''
- Rs.MoveFirst
- For ii = 0 To Rs.RecordCount - 1
- If Rs.Fields(2) > 1 Then
- Str = "Select Path "
- Str = Str & "From [Sheet1$J13:L54] "
- Str = Str & "Where Name = '" & Rs.Fields(1) & "'"
- Debug.Print Str
- Set Rs1 = SqlRetuRs(Str)
- aa = Rs1.GetRows()
- Rs1.MoveFirst
- With WorksheetFunction
- Sht.Cells(15 + ii, 5).Resize(, Rs1.RecordCount) = .Transpose(.Transpose(Rs1.GetRows()))
- End With
- End If
-
- Rs.MoveNext
- Next ii
-
- End Sub
复制代码
采用嵌套SQL没有实现。
- Sub ll()
- Dim Str, oStr
- Dim Rng As Range
- Set Rng = Selection
- Dim Sht As Worksheet
- Set Sht = Rng.Parent
- Set Rng = Sht.Range(Sht.Cells(7, 1).Formula)
- Debug.Print Rng.Address
- Rng.Clear
-
- Set Rng = Sht.Range(Sht.Cells(6, 1).Formula)
- Debug.Print Rng.Address
- SqlShtStr = Sht.Name & "$" & Rng.Address(0, 0)
-
- Dim Rs As ADODB.Recordset, Rs1 As ADODB.Recordset, Rs2 As ADODB.Recordset
- Dim StrSql, StrSql1, StrSql2
- StrSql1 = "Select Distinct Name From [" & SqlShtStr & "] Where Not Name is Null"
- Set Rs1 = SqlRetuRs(StrSql1)
- Debug.Print Rs1.RecordCount
-
-
- ''
- StrSql = "Select oDate,Name,Path,Count(Name) From ("
- StrSql = StrSql & "Select oDate,Name,Path,Count(Name) From [" & SqlShtStr & "] where Not Name is Null Group by oDate, Name,Path "
- StrSql = StrSql & ") AS A where "
-
- Rs1.MoveFirst
- oStr = "Name = '" & Rs1.Fields(0) & "'"
- Rs1.MoveNext
- For ii = 1 To Rs1.RecordCount - 1
- oStr = oStr & " Or Name = '" & Rs1.Fields(0) & "'"
- Rs1.MoveNext
- Next ii
- StrSql = StrSql & oStr & " Group by oDate,Name,Path"
- Debug.Print StrSql
-
- Set Rs = SqlRetuRs(StrSql)
- Sht.Cells(15, 1).CopyFromRecordset Rs
- End Sub
复制代码
|
|