How to use a variable for the criteria in a query to restrict the query to the active form? - ms-access-2013

I have form named "frmBond-MuniDetailsAE". It has a combo box named "cboStep". The Row Source for cboSteps is an embedded query that retrieves records from a table named "tblBond-Steps", and it has as Criteria -
[Forms]![frmBond-MuniDetailsAE]![SYM]. This restricts the query to records in tblBond-Steps to only those that have a SYM field that matches that field in the form. This works fine. But I would like to be able to copy and reuse the form for other types of bonds, and I don't want to have to rewrite the embedded query in each copied form. So I wanted to use a variable in the query criteria that would reference the current form.
Following answers given in StackOverflow at How do I reference the current form in an expression in Microsoft Access?, I wrote a Public Function named "FormName()". Here is the function:
Public Function FormName() As String
Dim frmCurrentForm As Form
Set frmCurrentForm = Screen.ActiveForm
FormName = "[Form]![" & frmCurrentForm.Name & "]" & "![SYM]"
End Function
Then in the embedded query for the combo box, I entered "FormName()" as the criteria. Here is the SQL for that query:
SELECT [tblBond-Steps].SYM, [StepDate] & " # " & [Cpn] AS Steps, Format([tblBond-Steps].
[StepCpn],"0.0000%") AS Cpn, [tblBond-Steps].StepDate
FROM [tblBond-Steps]
WHERE ((([tblBond-Steps].SYM)=FormName()))
ORDER BY [tblBond-Steps].StepDate;
But when I open the form with the above query as the Row Source for cboSteps, I get VBA Run-time error '2475': "You entered an expression that requires a form to be the active window."
I can't figure out what I'm doing wrong. Can someone help me?

You must return the value, not the expression:
Public Function FormName() As String
Dim frmCurrentForm As Form
Set frmCurrentForm = Screen.ActiveForm
FormName = frmCurrentForm![SYM].Value
End Function

Related

VBA function to get windows user name [duplicate]

I would like to know if there is a way to get system username and use it directly in an MS Access query. I have made a parameter work within a query from a combo box on a form and I have also acquired system name in Access VBA using ENVIRON ("USERNAME").
Kindly let me know if this is possible.
You need to create a VBA function that returns the username, and then use the function in the query.
Public Function GetUserName() As String
' GetUserName = Environ("USERNAME")
' Better method, see comment by HansUp
GetUserName = CreateObject("WScript.Network").UserName
End Function
and
SELECT foo FROM bar WHERE myUserName = GetUserName();
My solution kept all the work in VB.
I used a variable for the windows login username and then created a SQL string with that variable inserted. Lastly, I updated the query behind the form to use this new SQL string.
The CHR(34) puts quotes around the name as it is now a string inside the SQLSTR and needs to be within a set of quotes.
If you have a complex SQL statement, write it in the QBE using a string for the name and all the other variables, then switch to the SQL view and replace it using a VBA variable as shown below.
MyName = Environ("username")
sqlstr = "SELECT * From Projects WHERE ( ((Projects.LeadEngineer)=" & Chr(34) & MyName & Chr(34) & " AND ActiveYN = True ));"
Forms![Main Form].RecordSource = sqlstr
You can use SYSTEM_USER if the query is being executed in a SQL Server, that will retrieve the user name connected to the database (for that, make sure you are not using fixed user name in your connection string)
Yes - you can use the 'CurrentUser' function in your query. Here I've included it as a field and criteria.
SELECT Field1, Field2, [CurrentUser] AS UserName FROM Table1 WHERE Field1 = [CurrentUser];

Getting value of database field in Crystal Reports

Currently I'm working on legacy application, that uses crystal report engine. I have to get value of database fields programmatically. As I've assumed, I need proper event for getting next code to work:
Report.Database.Tables(1).Fields(1).Value
But the value is always empty in DownloadStarted/Finished event handlers. What I'm doing wrong and is it at least possible?
I think that if you want to get value of your table fields in program the best way is that you get the field name from report and then connect to your table directly and use report field names as the table columns name
i do it in c# i hope it can help you in vb6 too:
string name = report2.Database.Tables[1].Fields[1].Name;
string[] names = name.Split('.');
and then add your database to your program and use names like this:
DataTable dt = new DataTable();
string[] value = dt.Columns[names[1]];
if you just need your tables values, you can use my last answer, but if you need value of database fields in crystal report, i mean something like formula field ,this code can help you:
CRAXDRT.FormulaFieldDefinitions definitions = report2.FormulaFields;
string formulaText = "IF " + report2.Database.Tables[1].Fields[3].Name
+ " > 10 THEN" + report2.Database.Tables[1].Fields[2].Name;
definitions.Add("Test", formulaText);
report2.Sections[1].AddFieldObject(definitions[1], 0, 0);

Query Disconnected RecordSet

Background: a LOB app we use has the ability to use macros written in VBScript, but no access to WScript, etc., as far as I know.
I have successfully received user input, passed it to a stored procedure on a SQL Server, and returned a recordset to the VBScript macro in the application.
What I want to do now, is write a function or loop or something, that for as long as there is a record left in the recordset, accept additional user input, and check this against the returned recordset.
The recordset returned from SQL Server contains two columns: PART_ID and PART_QTY. For as many number of entries there are, I want to accept additional user input, lets say PART_ID_INPUT and PART_QTY_INPUT, and validate it against the in-memory recordset.
My biggest problem is working with the disconnected recordset.
When in doubt, read the documentation. You can use the Filter and RecordCount properties to determine if the recordset contains matching records:
part_id_input = InputBox("Enter part ID:")
If part_id_input <> "" Then
rs.Filter = "PART_ID = '" & part_id_input & "'"
If rs.RecordCount > 0 Then WScript.Echo "Found matching record."
End If
The filter is cleared by setting it to an empty string:
rs.Filter = ""
The current record can be removed from the recordset using the Delete method:
rs.Delete
Navigate through records via MoveFirst/MoveLast/MoveNext/MovePrevious.

"Query is not understandable" - Full text searching where field types have changed

A client have a long lived IBM Notes application where someone along the line changed the type of a field from number to text.
So, now when we're trying to do an FT search like: [myField] = "1234" receive the error message: "Query is not understandable".
If I do: [myField] = 1234 it works but won't return any hits. Even though there's a document where myField = "1234".
The field is of type text in the design.
I've created a new view for testing, only allowing documents from one form.
Deleted the full text index (even on the file system)
updall -X
Fixup -r
Created full text index
In my test view I've got one column that shows if the field content being searched is of type text #IsText(myField) and all rows shows: 1 (so it's field content must be text)
None of the above worked so I created a new database copy locally.
Same problem.
Created an entirely new database (for testing only), form, view and full text index and that works.
Feels like the existing database design somewhere stores the old field type...
Any ideas appreciated.
Thanks!
/J
Datatypes and field names are stored in the UNK table. There is just one entry per field name, so it's critical not to use the same field name more than once in an application with different datatypes.
You need to rebuild the UNK table, as I blogged here http://www.intec.co.uk/full-text-search-musings/
Note, it must be an offline compact, as Duffbert says here http://www.duffbert.com/duffbert/blog.nsf/d6plinks/TDUF-5SMHV4. If anyone is in the database when you do the compact, it will fail and the UNK table will not be rebuilt.
Links are useful, but if you don't want to remove data from documents - for me such steps worked (and there was no need in removing fields from forms in designer):
Run from designer with manager access with such code inside
Sub Initialize
Dim s As New NotesSession
Dim db As NotesDatabase
Dim dc As NotesDocumentCollection
Dim doc As NotesDocument
Dim i As Integer
Dim nc As NotesNoteCollection
Dim noteid As String
Dim nextnoteid As string
Dim itemArr As Variant
Dim NeedSave As Boolean
Const ITEM_NAME = "itemName1|itemName2"
itemArr = Split( ITEM_NAME, "|" )
'погромист-кун не должен забывать про наличие итемов в формах...
Set db = s.Currentdatabase
Set nc = db.CreateNoteCollection(False)
nc.SelectForms = true
Call nc.BuildCollection
noteid = nc.Getfirstnoteid()
For i = 1 To nc.Count
Set doc = db.Getdocumentbyid( noteid )
noteid = nc.Getnextnoteid( noteid )
NeedSave = false
ForAll IA In itemArr
If doc.Hasitem( IA ) Then
Call doc.Removeitem( IA )
NeedSave = true
End If
End ForAll
If NeedSave Then
Call doc.Save( True, False )
End If
Print CStr( i ) & "\" & CStr( nc.Count )
Next
End Sub
Remove database index
Run from administrator command lo compact database.nsf -c , like mentioned in links above
Create index

Using variables instead of objects

I used this line
.RecordSource = "select * from tblpersonal where empid like '" & Me.lblIDNumber.Caption & "*'"
...my question is, what if I use a variable (varIDNumber) instead of object (lblIDNumber), what would be the syntax? I am using VB6.0
You didn't mention txtIDNumber in the code -- you mentioned lblIDNumber. I assume you mean for those two to be the same. In other words, the code you have at present should be something like this:
.RecordSource = "select * from tblpersonal where empid like '" & Me.txtIDNumber.Text & "*'"
So you are using the value of a text box in a form to populate the SQL query. Am I right so far?
And you are asking, what if I store the ID number in a variable rather than a text field? I agree, this is probably a step in the right direction.
So you might create a variable in the "General Declarations" section of the form using:
Dim idNumber As Integer
With the idea being to update the value of that variable each time the text field changes. Note: I am assuming that the "ID number" is an integer -- if not, you should use a String instead.
Now you need to update that variable when the text field changes. In the txtIDNumber_Change event, you will want to add code to convert the string txtIDNumber.Text into an Integer, and store it in idNumber. I forget the exact syntax, but I am guessing something like:
idNumber = Int(txtIDNumber.Text)
Finally, you can now use the idNumber variable in the SQL query rather than the text box:
.RecordSource = "select * from tblpersonal where empid like '" & idNumber & "*'"
Replace Me.lblIDNumber.Caption with varIDNumber
If you have a constant in the label and would prefer for the constant to be stored in a variable instead, create a Const in the form's code. Let's say the label has the text "43" in it.
In the general declarations section of the form, add the code:
Const idNumber As Integer = 43
Then, when constructing the query:
.RecordSource = "select * from tblpersonal where empid like '" & idNumber & "*'"
This will construct the query using the constant 43. I don't really see the point of this -- if you want the employee number to be something the user can type in, see my other answer.

Resources