我使用以下代码查询excel以获取符合特定条件的行:
For i = 90 To Worksheets("My Sheet").Range("E65536").End(xlUp).Row
' This for loop is to iterate through the list of dates in the excel sheet
Value = Worksheets("My Sheet").Range("E" & i).Value - #1/1/1900# + 2
'Using the above line i am converting the date i want to filter the date
'into numeric
strQuery = "SELECT * FROM [My another sheet$A3:I" & LastRow & "] WHERE [Date1]< " &
Value & " AND ([somefield] = 'dog' or [somefield] = 'cat')"
' Here in the SQL query i am trying to see how many cats and dogs are satisfying with my date criteria
Set rs = New ADODB.Recordset
With rs
.ActiveConnection = cn
.Source = strQuery
.CursorType = adOpenDynamic
.CursorLocation = adUseClient
.LockType = adLockOptimistic
.Open
End With
' Executing the select query on excel as database using ADODB api
If rs.RecordCount = 0 Then
Else
rs.MoveLast
End If
Worksheets("My Sheet").Range("F" & i).Value = rs.RecordCount
rs.Close
' Moving to the next date in the list
Next
我有类似这样的数据
我的列表中有这样的日期
for循环的目的是迭代这些日期并修改select查询 这是我从上面的代码中收到的值
32
35
37
44
57
64
71
78
84
86
89
91
91
但我应该得到这些价值观
32
36
37
47
57
66
73
81
84
89
90
91
91
我读过这样的地方,我们应该在使用记录计数属性之前发出命令rs.movelast
但是它仍然在某些迭代中显示错误的结果..
是因为循环而我使用相同的记录集。
我知道计数的原因应该是因为我只对excel列进行了相同的过滤并显示了不同的计数
列中没有数据类型更改,即每列从头到尾具有相同的数据结构
请帮我解决这个问题。
我希望问题很明确。如果需要更多详细信息,请告诉我。
答案 0 :(得分:1)
试试这个。它消除了循环。 Sheet7有一个日期列表,Sheet8有数据。
Sub groupbydate()
sSQL = "TRANSFORM Count(b.Dates) AS CountOfDates " _
& "SELECT 'Total' AS Total " _
& "FROM [Sheet7$] a, [Sheet8$] b " _
& "WHERE b.Animal In ('cat','dog') " _
& "AND b.[dates]<=a.[dates] " _
& "GROUP BY 'Total' " _
& "PIVOT a.Dates"
strFile = ActiveWorkbook.FullName
strCon = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & strFile _
& ";Extended Properties=""Excel 8.0;HDR=Yes;IMEX=1"";"
''Late binding, so no reference is needed
Set cn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")
cn.Open strCon
rs.Open sSQL, cn, 3, 3
For i = 1 To rs.Fields.Count
Worksheets("Sheet8").Cells(1, 5 + i) = rs.Fields(i - 1).Name
Next
Worksheets("Sheet8").Cells(2, 6).CopyFromRecordset rs
''Tidy up
rs.Close
Set rs = Nothing
cn.Close
Set cn = Nothing
End Sub