Help with This Code

S

SF

Hi,

I am traying to build a criteria string from a table that contain selected
ID (eg [ID]=1 or [ID]= 58 or [ID] =74 and so on).

I have code below that seem never work

Dim Stg As String
Dim dbs As DAO.Database
Dim rst As DAO.Recordset
Dim I As Long

Set dbs = CurrentDb
Set rst = dbs.OpenRecordset("tmpSelected", dbOpenDynaset)
With rst
Do While Not .EOF
Stg = "[ID] = " & .Fields(0) & " Or [ID] = "
.MoveNext
Loop
End With
Debug.Print Stg

Could somebody advice

SF
 
R

Robert Morley

Just a few small changes...changes are commented.

Dim Stg As String
Dim dbs As DAO.Database
Dim rst As DAO.Recordset
Dim I As Long

Set dbs = CurrentDb
Set rst = dbs.OpenRecordset("tmpSelected", dbOpenDynaset)
With rst
'Add next line (not absolutely necessary, but good practice
Stg = ""
Do While Not .EOF
'Change next line to
Stg = Stg & " Or ([ID] = " & .Fields(0) & ")"
.MoveNext
Loop
End With
'And add this (strips off the leading " Or ", leaving you with a correctly
formatted string)
If Stg <> "" Then Stg = Mid$(Stg, 5)
Debug.Print Stg


Alternately, you can use an "In" statement, which isn't much different to
build, but will execute faster than a whole bunch of Or's:

Dim Stg As String
Dim dbs As DAO.Database
Dim rst As DAO.Recordset
Dim I As Long

Set dbs = CurrentDb
Set rst = dbs.OpenRecordset("tmpSelected", dbOpenDynaset)
With rst
'Add next line (not absolutely necessary, but good practice
Stg = ""
Do While Not .EOF
'Change next line to
Stg = Stg & "," & .Fields(0)
.MoveNext
Loop
End With
'And add this (strips off the leading " Or ", leaving you with a correctly
formatted string)
If Stg <> "" Then Stg = "In(" & Mid$(Stg, 2) & ")"
Debug.Print Stg
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

Code wont work 2
VBA works in orignal but fails in copy of database 1
Runtime error 91 2
Excel workbook and printing 3
Working outlook via vba code with xlsx - error 0
Code won't work 1
Help with code 2
Error 3622 0

Top