我有一个想要针对表执行的查询。结果我想做点什么。在我的脑海中,伪代码是:
var q = "select * from table where some condition";
var results = db.getResults(q);
foreach (row r in results )
do something with result
我如何与vba类似?
答案 0 :(得分:29)
DAO是Access的原生,是迄今为止最常用的。 ADO有它的位置,但不太可能就是这样。
Dim rs As DAO.Recordset
Dim db As Database
Dim strSQL as String
Set db=CurrentDB
strSQL = "select * from table where some condition"
Set rs = db.OpenRecordset(strSQL)
Do While Not rs.EOF
rs.Edit
rs!SomeField = "Abc"
rs!OtherField = 2
rs!ADate = Date()
rs.Update
rs.MoveNext
Loop
答案 1 :(得分:0)
我知道AC 2010中的一些事情已经发生了变化。但是,据我所知,老式的ADODB是VBA的最佳选择。一个例子:
Dim cn As ADODB.Connection
Dim cmd As ADODB.Command
Dim prm As ADODB.Parameter
Dim rs As ADODB.Recordset
Dim colReturn As New Collection
Dim SQL As String
SQL = _
"SELECT c.ClientID, c.LastName, c.FirstName, c.MI, c.DOB, c.SSN, " & _
"c.RaceID, c.EthnicityID, c.GenderID, c.Deleted, c.RecordDate " & _
"FROM tblClient AS c " & _
"WHERE c.ClientID = @ClientID"
Set cn = New ADODB.Connection
Set cmd = New ADODB.Command
With cn
.Provider = DataConnection.MyADOProvider
.ConnectionString = DataConnection.MyADOConnectionString
.Open
End With
With cmd
.CommandText = SQL
.ActiveConnection = cn
Set prm = .CreateParameter("@ClientID", adInteger, adParamInput, , mlngClientID)
.Parameters.Append prm
End With
Set rs = cmd.Execute
With rs
If Not .EOF Then
Do Until .EOF
mstrLastName = Nz(!LastName, "")
mstrFirstName = Nz(!FirstName, "")
mstrMI = Nz(!MI, "")
mdDOB = !DOB
mstrSSN = Nz(!SSN, "")
mlngRaceID = Nz(!RaceID, -1)
mlngEthnicityID = Nz(!EthnicityID, -1)
mlngGenderID = Nz(!GenderID, -1)
mbooDeleted = Deleted
mdRecordDate = Nz(!RecordDate, "")
.MoveNext
Loop
End If
.Close
End With
cn.Close
Set rs = Nothing
Set cn = Nothing
答案 2 :(得分:0)
稀释。因为我错过了你最初的帖子,这里有一个也是ITERATES的例子。第一个例子没有。在这种情况下,我检索ADODB记录集,然后将数据加载到一个集合中,该集合由函数返回给客户端代码:
编辑:不知道我在粘贴代码时搞砸了什么,但格式化有点麻烦。遗憾!Public Function StatesCollection() As Collection
Dim cn As ADODB.Connection
Dim cmd As ADODB.Command
Dim rs As ADODB.Recordset
Dim colReturn As New Collection
Set colReturn = New Collection
Dim SQL As String
SQL = _
"SELECT tblState.State, tblState.StateName " & _
"FROM tblState"
Set cn = New ADODB.Connection
Set cmd = New ADODB.Command
With cn
.Provider = DataConnection.MyADOProvider
.ConnectionString = DataConnection.MyADOConnectionString
.Open
End With
With cmd
.CommandText = SQL
.ActiveConnection = cn
End With
Set rs = cmd.Execute
With rs
If Not .EOF Then
Do Until .EOF
colReturn.Add Nz(!State, "")
.MoveNext
Loop
End If
.Close
End With
cn.Close
Set rs = Nothing
Set cn = Nothing
Set StatesCollection = colReturn
结束功能