vba ADOBE.recordset筛选器/查找
我有一个Excel VBA中的ADOBE.Recordset,它是从查询返回到数据库的。我应该如何在这个集合中找到符合特定标准的特定记录?下面是代码。有人能帮我填写“打印出一个和我同龄的人的名字”部分吗?提前谢谢vba ADOBE.recordset筛选器/查找,vba,excel,Vba,Excel,我有一个Excel VBA中的ADOBE.Recordset,它是从查询返回到数据库的。我应该如何在这个集合中找到符合特定标准的特定记录?下面是代码。有人能帮我填写“打印出一个和我同龄的人的名字”部分吗?提前谢谢 Dim rs As ADOBE.Recordset q = "select name, age from people where country = 'US'" Set rs = conn.Execute(q) 'conn is an ADOBE.Connection For i =
Dim rs As ADOBE.Recordset
q = "select name, age from people where country = 'US'"
Set rs = conn.Execute(q) 'conn is an ADOBE.Connection
For i = 30 To 40
'print out the name of one person whose age is i
Next i
更新1:
谢谢KazJaw!我认为你的解决方案应该奏效。然而,我正在寻找一个更清洁的解决方案-
Dim rs As ADOBE.Recordset
q = "select name, age from people where country = 'US'"
Set rs = conn.Execute(q) 'conn is an ADOBE.Connection
For i = 30 To 40
name = rs.Find("age = i")!name 'this line is where I am not sure how to achieve
MsgBox name & "'s age is " & i
Next i
抱歉格式化。我是这个网站的新手,不知道如何正确地缩进For循环中的两行
更新2:
是的,卡兹贾夫,还有其他问题。“.Find”要求rs能够向后滚动,这要求其lockType设置为AdLockOptimium。我还没弄清楚是怎么回事。如果我这样做,我会发帖的
解决方案:
关键是使用rs.Open而不是conn.Execute并设置游标类型
Dim rs As ADOBE.Recordset
q = "select name, age from people where country = 'US' Order By i"
Set rs = New ADODB.Recordset
rs.Open Source:=q, CursorType:=adOpenStatic, ActiveConnection:=ThisWorkbook.conn 'conn is an ADOBE.Connection
For i = 30 To 40
name = rs.Find("age = i")!name 'this line is where I am not sure how to achieve
MsgBox name & "'s age is " & i
Next i
第一个解决方案,没有循环,您可以这样做,但您需要坚持@mehow建议,其中
年龄条件应在SQL查询中实现
'return all results as of cell A2, direction down+right, in activesheet
ActiveSheet.Range("A2").CopyFromRecordset rs
第二个解决方案,使用循环,而不是i的。下一个循环尝试下面的解决方案
Dim lRow as long
lRow=2
With rs
Do Until .EOF
'return only those which age equals to i
'if implemented in SQL query then you could get rid of if statement below
if .Fields(1).Value = i then
Cells(lRow, 1) = .Fields(1).Value
Cells(lRow, 2) = .Fields(2).Value
.MoveNext
lRow = lRow + 1
end if
Loop
End With
第三种解决方案。如果您真的需要使用。请找到方法
,然后按以下方式执行:
'...your loop here
rs.Find "age = " & i
name = rs(0)
MsgBox name & "'s age is " & i
'... rest of your code here
不幸的是,我不确定它是否有效。我认为您需要在SQL代码中按年龄对结果进行排序。如果不是,我希望一些年龄可以省略。可能会出现其他一些问题。因此,请尝试其他解决方案。在获取记录集之前过滤查询-利用where
子句。所以q=“从国家=‘美国’和年龄>10的人群中选择姓名、年龄”
谢谢大家!这正是我现在正在做的。但是,这样做会向数据库生成多个查询(我发布的示例代码中有11个查询),从而使应用程序运行缓慢。因为我的数据集不是很大,所以我想在一次查询中将我们所有人查询到一个记录集中,然后在需要使用其中某个特定记录时在内存中进一步过滤。使用所需的较小记录集仍然比过滤大记录集更有效。您想在哪里打印它?到连续的excel范围?非连续范围?即时窗口?任何地方都可以。让我们假设在MsgBox上显示它。我只需要知道“名字”。