I've got a subform (customersAnswersSub) inside of a main form (customersAnswers). Upon someone entering a new customerAnswersSub entry - I wanted it to check for duplicates first.
It has to check across 4 different fields to match first.
This is what I've got so far.
Private Sub Form_BeforeUpdate(Cancel As Integer)
Dim rsGlobals As ADODB.Recordset
Dim sql
Set rsGlobals = New ADODB.Recordset
sql = "Select * From CustomerAnswerD where subscriptionNo=" & _
Me.subscriptionNo & " AND journal=" & Me.Journal & _
" AND volume=" & Me.volume & " AND issue=" & Me.issue
rsGlobals.Open sql, CurrentProject.Connection, adOpenDynamic, adLockOptimistic, adCmdText
If Not rsGlobals.BOF And Not rsGlobals.EOF Then
MsgBox ("Already entered")
Cancel = True
Me.Undo
End If
End Sub
it doesn't do anything - just sits there. when I close the form it'll pop up a - id already exists box.
Any idea, i'm pretty unexperienced when it comes to Access VB.
thank you
it doesn't do anything - just sits there
Just checking, since you said you're inexperienced with Access ... the form update event is not triggered until the record save is attempted. That may not happen automatically as soon as the user enters data into all the fields. However, you can trigger the update by navigating to a different record in the subform, or by a method such as choosing Records->Save Record from Access' (2003) main menu.
I don't see anything wrong with your BeforeUpdate procedure. Still I would convert it use the DCount() function instead of opening an ADO recordset. (See Access' help topic for DCount)
Private Sub Form_BeforeUpdate(Cancel As Integer)
Dim strCriteria As String
strCriteria = "subscriptionNo=" & Me.subscriptionNo & " AND journal=" & Me.Journal & _
" AND volume=" & Me.volume & " AND issue=" & Me.issue
Debug.Print strCriteria
If Dcount("subscriptionNo", "CustomerAnswerD", strCriteria) > 0 Then
MsgBox ("Already entered")
Cancel = True
Me.Undo
End If
End Sub
That assumes your table's subscriptionNo, journal, volume, and issue fields are all numeric data types. If any of them are text type, you will need to enclose the values in quotes within strCriteria.
I added Debug.Print strCriteria so you can view the completed string expression in the Immediate Window. You can also troubleshoot that completed string by copying it and pasting it into SQL View of a new query as the WHERE clause.
Also, consider adding a unique index on subscriptionNo, journal, volume, and issue to your CustomerAnswerD table design. That way you can enforce uniqueness without relying solely on your form to do it. The index will also give you faster performance with the DCount function, or your original recordset SELECT statement.
If you keep your original recordset approach, close the recordset and set the object variable = Nothing before exiting the procedure.
Related
I have a form, myForm, that includes a subform, mySubform. The records in mySubform have a many to one relationship with the record source of the myForm, as expected, and There is a combobox in mySubform, myCombo, whose values is linked to one of the columns of the record source of mySubform.
I have been having difficulty to delete a record in mySubform, by erasing the current value in myCombo. I have put the code below under the OnChange event of myCombo (after trying many different alternatives).
Please not that I have simplified the delete query and the actual one works fine in the back-end (SQL Server). However, after performing the delete operation, I get this error when the execution reaches Me.Requery:
Error 3162 You tried to assign a Null value to a variable that is not a Variant data type.
Also, after having the degugger skip the Me.Requery and going back to the form, the deleted record shows "#DELETED" in every combobox and textbox for that particular record, and mySubform is not any good beyond that point.
I have looked up very many resources and tried different statements instead of Me.Requery, but none has worked so far. Help is much appreciated.
Private Sub myCombo_Change()
If IsNull(Me.myCombo.Text) Or Me.myCombo.Text = vbNullString Then
Dim strSql As String
strSql = "DELETE FROM mySubformRecordSource WHERE PrimaryKeyColumn= " & theCurrentPrimaryKeyValueForTheValueIn_MyCombo
CurrentDb.Execute strSql
Me.Requery
End If
End Sub
I solved the problem by putting Me.Dirty = False after reading this discussion:
Editing Record issues in Access / SQL (Write Conflict)
Private Sub myCombo_Change()
If IsNull(Me.myCombo.Text) Or Me.myCombo.Text = vbNullString Then
Me.Dirty = False
Dim strSql As String
strSql = "DELETE FROM mySubformRecordSource WHERE PrimaryKeyColumn= " & theCurrentPrimaryKeyValueForTheValueIn_MyCombo
CurrentDb.Execute strSql
Me.Requery
End If
End Sub
The form and subform work flawlessly now, but I still dont quite understand the complete logic behind the solution. It has something to do with Me.Dirty=False saving the changes to the content of a non-nullable (or nullable, both work fine) column before programmatically delete the entire record. How exactly though, I dont know and will appreciate input.
Not entering on the choices of used cursors etc I think that the solution could be simply "requery" the parent form called by the code of the subform.
But i also have found similar situation in past projects that i made (sorry not beeing exaustive, i'm not using VBA anymore) and the requery command was done on subform but from the main form code, something like this:
If local_procedures.deleteContratto(anagrafica_id_par, servizio_id_par) = OK Then
Me.subfrm_contratti_frm_anagrafica.Requery
...
In this case you could delegate parent form to call delete procedure and update logic (.Requery) of the child form, by mean of an event raised from subForm listen on parent for example.
For the sake of completeness i started hinting about cursors because i think it's the underlying reason for these kind of sync failures between recordsets, the parent form one and the child form one.
There are many advices about using dbSeeChanges with db.Execute on SQL Server backend and the resulting default cursors.
UPDATE
Here's a code snippet where a custom event is raised from child to be caught from parent that is delegated to execute code regarding the child.
This pattern doesn't break the parent-child/one-to-many logic, assuming parent has more decision power than child.
' in mySubform
' assuming theCurrentPrimaryKeyValueForTheValueIn_MyCombo is a Long ID
Public Event DeleteRequest(record_ID As Long)
Private Sub myCombo_Change()
If IsNull(Me.myCombo.Text) Or Me.myCombo.Text = vbNullString Then
RaiseEvent DeleteRequest(theCurrentPrimaryKeyValueForTheValueIn_MyCombo)
End If
End Sub
' in myForm
Private WithEvents frmMySubform As Form__mySubform
' you could have more instances of mySubform concerning different issues or subrecords and manage each one correctly ...
Private WithEvents frmMySubform2nd As Form__mySubform
Private Sub frmMySubform_DeleteRequest(record_ID As Long)
Dim strSql As String
strSql = "DELETE FROM mySubformRecordSource WHERE PrimaryKeyColumn= " & record_ID
CurrentDb.Execute strSql
With Me.frmMySubform.Form
.Requery
' ...
end With
End Sub
Private Sub frmMySubform2nd_DeleteRequest(record_ID As Long)
Dim strSql As String
strSql = "DELETE FROM my2ndSubformRecordSource WHERE PrimaryKeyColumn= " & record_ID
CurrentDb.Execute strSql
With Me.frmMySubform2nd.Form
.Requery
' ...
end With
End Sub
I am using an Access2010 project as frontend, referring to a MS SQL Server 2008 as backend. Within my Access project there is form frmKlientenÜbersicht. This form has a view abfKlientenÜbersicht as dataSource.
Now I am trying to get the current number of records showing up in my form by using this code:
Private Sub Form_Current()
Debug.Print "Form_Current: " & anzahlDatensätze
lblAnzahlDatensätze.Caption = anzahlDatensätze & " Klient(en)"
End Sub
Private Function anzahlDatensätze() As Integer
Dim rs As Recordset
Set rs = Me.RecordsetClone
rs.MoveLast
anzahlDatensätze = rs.RecordCount
End Function
This works fine until I am using some filters. If I am using any filter on my form, the number of records stays unchanged!
What do I have to change to get the current number of records showing up (if filtered or not)?
What is the reason why my code does not show the correct number of records?
EDIT: According to the given comments and answers I tried setting Count([pkKlient] onto a textbox (see new pic) and tried DCount("*", "abfKlientenÜbersicht", me.Filter) from within VBA Code.
Unfortunatelly it seems that the filterClause is not valid when using it as parameter value for DCount. (see pic for filterClause).
As you can see count(..) does not result in a correct number - and the filterClause (generated by access!!) seems not to be valid for use by DCount(..)
If someone wants to try it, on your own, just create an ADP, add a form, add a view, form dataSource is a view, set a filter, and try to get the number of records?!!
Looking forward for any comments/answers/hints!
with VBA, DCount will give you what you need
DCount("*", "MyTable", Me.Filter)
If you want to put this on the form, there's an easier way. use an unbound box, and set it to =count([FieldName])
This count should remain correct, regardless of if it's counted filtered records or not.
Some notes, there are a dozen things that could go wrong with this, it could hardly even be called tested. However, it was returning the correct count for me.
Apparently, the form filter just hides records, whereas this will apply a real filter. However, you need to get the format into the right shape for a valid filter. In the end, a WHERE statement would probably be easier.
Private Sub Form_ApplyFilter(Cancel As Integer, ApplyType As Integer)
With Me.Recordset
''Filter
If ApplyType = 1 Then
''Very, very roughly. Remove form name, use single quotes
''You will need a lot more code for safety
sfilter = Replace(Me.Filter, "[" & Me.Name & "].", "")
sfilter = Replace(sfilter, """", "'")
.Filter = sfilter
MsgBox "Recordset : " & Me.Recordset.RecordCount & vbCrLf _
& "Filtered : " & .RecordCount
Else
''Remove filter - ApplyType 0
.Filter = ""
End If
End With
End Sub
Additional note with similar caveats
You can also set a textbox to something on these lines:
=IIf([FilterOn]=True,DCount("id","ATable",
Replace(Replace([Filter],"[" & [Name] & "].",""),"""","'")),Count([id]))
(Remove the break in the line, it is cosmetic)
I have a main form, frm_Main, and it has a subform in it, subform_Child. When the main form is displayed the subform is shown as well, it's just blank because there's no data in it (which is perfectly fine). When the user clicks a button on the main form the code builds a SQL string that contains a WHERE clause based upon what the user has entered in a text box. So far so good, I've done this before. Now the part that I cannot figure out (because I haven't done it before) is populating that subform using the SQL just created! Building the SQL string is no problem, I just don't know Access VBA well enough to know what code to use to update the subform from the main form and have it display the recordset after the query runs.
Edit: It's my understanding that using a QueryDef isn't a recommended method, correct?
Here's what I did as it seems to be the only way to do it.
1) Built a query named "zqry_PlaceHolder". In my case this is the data set that is being used (only the WHERE will change). I did add a WHERE clause in this (WHERE dbo_project.projectid = "_") but only so it would return nothing so as not to delay the displaying of the main form.
2) In the subform set the Source Object to the query I just built, "Query.zqry_PlaceHolder". This is required.
3) When the user clicks the button on the main form the VBA code is run. It creates the WHERE clause in the string variable sWhereFilter and then adds it to the SQL string:
'Build SQL string
sSQL = Empty 'Ensure string is empty
sSQL = "SELECT Proj_Locs.ProjectID, dbo_PROJECTS.PROJECTID, Proj_Locs.Location, Master_Scans.FileName, Proj_Locs.Title, dbo_PROJECTS.TITLE" & vbCrLf
sSQL = sSQL & "FROM (tbl_Project_Locations AS Proj_Locs" & vbCrLf
sSQL = sSQL & " LEFT JOIN dbo_PROJECT AS dbo_PROJECTS ON Proj_Locs.ProjectID = dbo_PROJECTS.PROJECTID)" & vbCrLf
sSQL = sSQL & " LEFT JOIN tblMasterScans AS Master_Scans ON Proj_Locs.ProjectID = Master_Scans.Project" & vbCrLf
sSQL = sSQL & sWhereFilter
sSQL = sSQL & "ORDER BY Proj_Locs.ProjectID ASC, dbo_PROJECTS.PROJECTID ASC;"
Then I throw up a "Please wait" form to let the user know things are processing and set the RecordSource of the subform to the built SQL string:
DoCmd.OpenForm "frm_PleaseWait", acNormal
DoCmd.Hourglass True
DoCmd.RepaintObject acForm, "frm_PleaseWait" 'Needed to show everything in the form immediately, otherwise there's a delay
Me.subform_Results.Form.RecordSource = sSQL 'This updates the subform AND executes it, refreshing the results
Beep 'Let user know processing completed
Me.txt_RecordsReturned = Me.subform_Results.Form.Recordset.RecordCount 'Let user know how many records were returned with their query (if any)
This works and it does not change the placeholder query "zqry_PlaceHolder".
I hope this helps others as it wasn't as intuitive to me. If there is another/better method I'm all for learning something new!
Sorry for the wall of text guys but this one requires expliaining, way too much code to post...
I'm importing fixed width files into access in methods that require data entry. I import the file using transferText into two specs (ones global, the other is special circumstance).
I have a function that uses DAO to cycle through all Field objects in TableDefs to build a duplicate table including an AutoIncrement PK so I have the ability to edit these records. I push the data into that table with INSERT INTO.
Works great. Errors are found, user goes into data entry to manually correct them which beats sifting through 400 character lines and reorganizing everything the way its supposed to be. Works great!
The problem: When the data entry changes are made a commit button is pressed which calls a function inside a module outside of the form. It closes the data entry form and pushes the information back to the original table minus the autoincremented PK, and is SUPPOSED to DROP the replicated table with ID's, and generate a new one searching once again for errors...
It pushes back to the original just fine, but it will not DROP the ID table. Always returns to me with a message indicating this table is locked. Ive noticed the table is indefiniatly locked down until all functions/subs exit. At any time stepping through the code I cannot delete it manually, once the execution has finished I am able to remove it.
I am assuming that since I called this through a command in the form, that the lock will not be released until all code finishes and the form terminate can be called and do its thing. Any thoughts? Yes this is very barbaric but it works quite well, I just need to be able to rip this other table off the planet so I can redrop an updated copy...
In the worst case I can make the user close the form out and hit another button in the main form but this is being designed heavily with user compitence in mind. However this now has my full attention and would like to at least find a solution even if it's not the optimal one.
-EDIT-
Two forms are used in this problem
FormA (Role: Load in and search for problems)
Examine button is pressed that:
- Uses TextTransfer based on predefined specs into tempExtract to
import the file
- DAO fires off on the Fields collection in tableDefs for
tempExtract, creates new table tempExtractID
- Performs searches through the file to find errors. Errors are saved to
a table Problem_t. Table contains Problem_ID (Set from the ID field
added to tempExtractID) and Description
- Execution of these tasks is successfully requerying the initial
form to showing a list of problems and number of occurances. A button
gains visibility, with onClick that opens the form DataEntry.
- At this point in the code after DAO execution, I can DROP the table
tempExtractID. DAO is NOT used again and was only used to build a new table.
FormB - Data Entry Form
As soon as I open this form, the table tempExtractID becomes locked and I cannot drop the table. The recordsource to the form querys tempExtractID against the ID's in Problems_t to return only what we need to key.
I cannot drop the table until the form has fully terminated. Button on the Data Entry form is pressed to commit changes, in which there are only 5 lines of code that get to fire off before I get my lock error.
*Xargs refers to the list of Field names pulled earlier through DAO. As DAO loops through Field objects, the physical names are added to an Xargs String which is placed in this table. Basically everything but the AutoNumber is being inserted back
docmd.Close acForm, "frmDataEntry", acSaveNo
call reInitializeExtract
> docmd.RunSQL "DELETE FROM tempExtract"
> docmd.RunSQL "INSERT INTO tempExtract SELECT (" & DLookup("Value", "CONFIG_t", "Item = 'Xargs'" & ") FROM tempExtractID"
docmd.DeleteObject acTable, "tempExtractID"
This is the only code that is run between the time where the form is opened (Where the table first gets locked) and continues to be locked until all subs & functions have completed.
I suggest setting the recordsource of the form to vbNullString and then deleting the table. This should work, unless you also have comboboxes and so forth bound to this table.
Without code it's hard to say, but if you're using DAO, you need to clean up your code objects. That means setting to Nothing your database objects, and closing and setting to Nothing any recordset objects.
Dim db As DAO.Database
Dim rs As DAO.Recordset
Set db = DBEngine.OpenDatabase("[path to database]")
Set rs = db.OpenRecordset("[SELECT statement]")
rs.Close
Set rs = Nothing
db.Execute("[DML or DDL statement]", dbFailOnError)
db.Close
Set db = Nothing
Set db =CurrentDB
Set rs = db.OpenRecordset("[SELECT statement]")
rs.Close
Set rs = Nothing
Set db = Nothing ' you don't close a db variable initialized with CurrentDB
While VBA is supposed to clean up these objects when they go out of scope, it's not 100% reliable (because VBA uses reference counting to keep track of whether an object can be released, and it doesn't always know when all the references have been cleared).
Objects left open is the most likely source of the locks, so you should make sure you're cleaning up your object variables after you've finished with them.
EDIT after seeing that you're using DoCmd.RunSQL:
Using DoCmd.RunSQL is likely the cause of the problem. It is certainly something that takes away your programmatic management of your connections. If you use DAO instead, you'll have control over the connection, as well as avoiding the real pitfall of DoCmd.RunSQL, which is that it doesn't handle errors. If a DML or DDL statement cannot complete successfully in full, the whole thing should fail. For example, if you're appending 100 records and 10 of them fail for key violations, DoCmd.RunSQL will transparently append the 90 and NOT REPORT THE 10 FAILURES. It's the same with updates and any other DML/DDL statement. DoCmd.RunSQL "helpfully" silently completes as many of the updates as it can, leaving you having no idea that some of it failed to complete.
Granted, in some cases you might want that to happen, e.g., if you're appending records that you know might have PK collisions and don't want to spend the CPU cycles on an outer join that eliminates the duplicates from the set of records you're appending.
But most of the time, that is not the case.
As I said in my comment above, I use a function that is designed to transparently replace DoCmd.RunSQL and uses a DAO Execute statement and error handling. I have posted it a couple of times on SO (here's one), and here's the version I have in production use in my currently most-active development project:
Public Function SQLRun(strSQL As String, Optional db As Database, _
Optional lngRecordsAffected As Long) As Long
On Error GoTo errHandler
Dim bolCleanup As Boolean
If db Is Nothing Then
Set db = CurrentDb
bolCleanup = True
End If
'DBEngine.Workspaces(0).BeginTrans
db.Execute strSQL, dbFailOnError
lngRecordsAffected = db.RecordsAffected
'DBEngine.Workspaces(0).CommitTrans
exitRoutine:
If bolCleanup Then
Set db = Nothing
End If
SQLRun = lngRecordsAffected
'Debug.Print strSQL
Exit Function
errHandler:
MsgBox "There was an error executing your SQL string: " _
& vbCrLf & vbCrLf & Err.Number & ": " & Err.Description, _
vbExclamation, "Error in SQLRun()"
Debug.Print "SQL Error: " & strSQL
'DBEngine.Workspaces(0).Rollback
Resume exitRoutine
End Function
(the transactions are commented out because they were causing problems that I didn't have time to troubleshoot)
You could replace these lines of yours:
DoCmd.RunSQL "DELETE FROM tempExtract"
DoCmd.RunSQL "INSERT INTO tempExtract SELECT (" _
& DLookup("Value", "CONFIG_t", "Item = 'Xargs'" & ") FROM tempExtractID"
...with this:
SQLRun "DELETE FROM tempExtract"
SQLRun "INSERT INTO tempExtract SELECT (" _
& DLookup("Value", "CONFIG_t", "Item = 'Xargs'" & ") FROM tempExtractID"
You could also do this:
Debug.Print SQLRun("DELETE FROM tempExtract") & " records deleted."
Debug.Print SQLRun("INSERT INTO tempExtract SELECT (" _
& DLookup("Value", "CONFIG_t", "Item = 'Xargs'" _
& ") FROM tempExtractID") & " records inserted."
Since the function returns the .RecordsAffected for each Execute, you can print to the Immediate Window, or you could assign the return value to a variable, or pass an existing variable through to it and work with that variable thus:
Dim lngRecordsAffected As Long
...
Call SQLRun("DELETE FROM tempExtract", , lngRecordsAffected)
Debug.Print lngRecordsAffected & " records deleted."
Call SQLRun("INSERT INTO tempExtract SELECT (" _
& DLookup("Value", "CONFIG_t", "Item = 'Xargs'" _
& ") FROM tempExtractID", , lngRecordsAffected)
Debug.Print lngRecordsAffected & " records inserted."
The point is that if there are errors on the Execute statement, the whole thing will fail (and pop up an error message -- you might want to change it so that if there's an error it returns -1 or some such instead of popping an MsgBox).
I use this function most often by passing in a pre-cached database variable, so I don't want to clean it up afterwards. If you're using a different database other than CurrentDB(), you really do want to make sure any database variable pointing to your external db is closed and set to Nothing. Without that, locks are maintained on the top-level database objects, and the LDB file remains open and active.
HI,
I am trying to write a query in vba and to save its result in a report.
I am a beginner. this is what i have tried
can somebody correct me
Dim cn As New ADODB.Connection, rs As New ADODB.Recordset
Dim sql As String
Set cn = CurrentProject.Connection
sql = "Select * from table1 where empno is 0"
rs.Open sql, cn
While Not rs.EOF
' here i think i should save the result in a report but i am not sure how
rs.MoveNext
Wend
rs.Close
cn.Close
Set rs = Nothing
Set cn = Nothing
Also how do i change this query to run this on all tables in a database
IF you are wanting to create a report using MS Access's report generator, you will have to use a Query Object (there might be a way to trick MS Access into running it off of your record set, but it's probably not worth your effort).
You can create the Query Object on the "Database" window. Click the Query button in the objects list, and then click on New. In the resulting editor you can create the query graphically or if you prefer with SQL. Save the query and give it a meaning full name.
Similarly the report can be created on the "Database" window. Click on the Report button and then on New. In the resulting wizard, you'll link the report to the query you just created.
Update: As D.W. Fenton said, you can embed the query right within the Report Object without creating a separate Query Object. My preference is to create one anyway.
The problem with this method is you would have to create a separate query and report for each table.
IF you just want to dump the result out to a text file (to read/print later), then you can do it using recordsets like you are in your VBA code. It will look something like this
'...
dim strFoo as string
dim strBar as string
'...
if not rs.bof then
rd.MoveFirst
end if
While Not rs.EOF
strFoo = rs("foo") 'copy the value in the field
'named "foo" into strFoo.
strBar = rs("bar")
'... etc. for all fields you want
'
'write out the values to a text file
'(I'll leave this an exercise for the reader)
'
rs.MoveNext
Wend
'...
Parsing all of the tables can be done in a loop something like this:
dim strTableName as string
dim db As Database
'...
Set db = CurrentDb
db.TableDefs.Refresh
For Each myTable In db.TableDefs
If Len(myTable.Connect) > 0 Then
strTableName = myTable.Name
'...
'Do something with the table
'...
End If
Next
set db = nothing
=======================UPDATE=======================
It is possible to run an MS-Access Report from a record set. To repease what I said to tksy's question
From Access Web you can use the "name" property of a recordset. You resulting code would look something like this:
In the report
Private Sub Report_Open(Cancel As Integer)
Me.RecordSource = gMyRecordSet.Name
End Sub
In the calling object (module, form, etc.)
Public gMyRecordSet As Recordset
'...
Public Sub callMyReport()
'...
Set gMyRecordSet = CurrentDb.OpenRecordset("Select * " & _
"from foo " & _
"where bar='yaddah'")
DoCmd.OpenReport "myReport", acViewPreview
'...
gMyRecordSet.Close
Set gMyRecordSet = Nothing
'...
End Sub
Q.E.D.
Normally you would design the report based on a data source. Then after your report is done and working properly you use VBA to display or save the report.
To run this for each table in the database, I'd suggest writing a function that looped through CurrentData.AllTables(i) and then called your function above in each iteration
Hope this helps
If you want to simply view the results, you can create a query. For example, here is some rough, mostly untested VBA:
Sub ViewMySQL
Dim strSQL as String
Dim strName As String
'Note that this is not sensible in that you
'will end up with as many queries open as there are tables
For Each tdf In CurrentDB.TableDefs
If Left(tdf.Name,4)<>"Msys" Then
strName = "tmp" & tdf.Name
strSQL = "Select * from [" & tdf.Name & "] where empno = 0"
UpdateQuery strName, strSQL
DoCmd.OpenQuery strName, acViewNormal
End If
Next
End Sub
Function UpdateQuery(QueryName, SQL)
If IsNull(DLookup("Name", "MsysObjects", "Name='" & QueryName & "'")) Then
CurrentDb.CreateQueryDef QueryName, SQL
Else
CurrentDb.QueryDefs(QueryName).SQL = SQL
End If
UpdateQuery = True
End Function
You may also be interested in MDB Doc, an add-in for Microsoft Access 97-2003 that allows you to document objects/properties within an Access database to an HTML file.
-- http://mdbdoc.sourceforge.net/
It's not entirely clear to me what you want to do. If you want to view the results of SQL statement, you'd create a form and set its recordsource to "Select * from table1 where empno is 0". Then you could view the results one record at a time.
If that's not what you want, then I'm afraid I just don't have enough information to answer your question.
From what you have said so far, I don't see any reason why you need VBA or a report, since you just want to view the data. A report is for printing, a form is for viewing and editing. A report is page-oriented and not that easy to navigate, while a form is record-oriented, and allows you to edit the data (if you want to).
More information about what you want to accomplish will help us give you better answers.
Had the same question. just use the clipboard!
select the query results by click/dragging over all field names shown
press ctrl-c to copy to windows clipboard
open a blank document in word and click inside it
press ctrl-v to paste from clipboard.