Receiving Null when attempting to retrieve checkbox values from Access table - ms-access

What I did was append the checkboxes as additional columns of a query which was then used to create a recordset. This recordset was then assigned to a combobox control.
Previously, it worked fine for me to then reference columns of the selected row in the combobox that were not displayed. However, no matter what I try, when I attempt to reference these checkboxes, all I get is a null value.
To illustrate:
Set rs = db.OpenRecordset("SELECT AG.Acttype, AG.ActGroupID, AT.HasLots, AT.IsLotSrce, " _
& "AT.HasStructs FROM ActivityGroup AG, ActivityType AT WHERE (" _
& FormatToSQLVal(Me![WizardSubformDisplay].Form![ActLinkedProjInput].Column(1)) _
& " = AG.ProjectID) AND (AG.Acttype = AT.ActType);")
Set Me![WizardSubformDisplay].Form![ActTypeInput].Recordset = rs
(in this case there is the additional following tinkering which didn't cause trouble for other cases that didn't deal with checkboxes)
Me![WizardSubformDisplay].Form![ActTypeInput] = Me![ActTypeName]
Me![WizardSubformDisplay].Form![ActTypeInput].Locked = True
(I set the combobox to a specific choice and then lock it)
Me![WizardSubformDisplay].Form![ActTypeInput].Column(2),
Me![WizardSubformDisplay].Form![ActTypeInput].Column(3),
Me![WizardSubformDisplay].Form![ActTypeInput].Column(4)
all return null, rather than -1 if the box is checked and 0 otherwise.

Related

Access Tab Control - Set Pages Visibilty based on Subform Records

I know how to do this, but wondering if I might be able to write a more elegant solution. I have a form with a tab control. The control has 14 pages, each one, with it's own sub form. One of the pages (pgRequirements) has a subform of requirements, with a combo control "Requirement Type". It is a continuous form, so the user can add as many requirements as they want, for the main record.
There are 9 of those requirements, which have their own tab control page / sub form. I want to set visibility of those tab control pages, based on this parent's sub form requirements. So a current main record, can have multiple sub-requirement records. If any of those match e.g. requirement type A, than page A should be visible, otherwise it should not be.
I need this code to run anytime the main form is loaded, and the detail is made visible (meaning a main record has been chosen from a find form). Also anytime a requirement record is added or removed. The below is assuming that the parent-child links on the main form to subform will limit the requirement records, to just those that are for the current main record.
Here is the simple code, that will do the job, but is probably over-written:
If Me.FKRequirementType.Column(1) = "ReqType1" Then
Me.Parent!pgReqType1.Visible = True
Else
Me.Parent!pgReqType1.Visible = False
End If
If Me.FKRequirementType.Column(1) = "ReqType2" Then
Me.Parent!pgReqType2.Visible = True
Else
Me.Parent!pgReqType2.Visible = False
End If
If Me.FKRequirementType.Column(1) = "ReqType3" Then
Me.Parent!pgReqType3.Visible = True
Else
Me.Parent!pgReqType3.Visible = False
End If
If Me.FKRequirementType.Column(1) = "ReqType4" Then
Me.Parent!pgReqType4.Visible = True
Else
Me.Parent!pgReqType4.Visible = False
End If
Thanks!
EDIT
I turned this into a public function, so I can call it from anywhere. One problem. It's not working lol (small problem). I don't get any errors, but all the tab control pages are visible. When I add a new record, most of them should be hidden. I have a tblReqType table, with all the requirement types. I added a column to this, with the exact name of it's corresponding tab control page name, so I can loop through that table, for all records where that page name is not null, and set their page visible or not, based on the current main record ID having a record-requirement (cross reference table) record for each requirement type.
This is the public function I wrote. Can anyone help me understand what I'm missing in these loops for setting the visibility true (vtrue) vs setting the visibility false (vfalse)
Public Function ShowRequirements()
Dim db As DAO.Database
Dim strRstVTrue As String
Dim rstvTrue As DAO.Recordset
Dim strRstVFalse As String
Dim rstvFalse As DAO.Recordset
Dim strFieldName As String
'Setup the recordset
Set db = CurrentDb
strRstVTrue = "SELECT tblMRecordRequirements.ID, tblMRecordRequirements.FKMC, tblReqType.txtRequirementPage " & _
"FROM tblMRecordRequirements LEFT JOIN tblReqType ON tblMRecordRequirements.FKRequirementType = tblReqType.ID " & _
"WHERE tblReqType.txtRequirementPage Is Not Null AND tblMRecordRequirements.FKMC = " & Nz(Forms!frmMRecords!ID, 0)
strRstVFalse = "SELECT tblReqType.ID, tblReqType.txtRequirementPage, tblMRecordRequirements.FKMC " & _
"FROM tblReqType LEFT JOIN tblMRecordRequirements ON tblReqType.ID = tblMRecordRequirements.FKRequirementType " & _
"WHERE tblReqType.txtRequirementPage Is Not Null AND tblMRecordRequirements.FKMC <> " & Nz(Forms!frmMRecords!ID, 0)
Set rstvTrue = CurrentDb.OpenRecordset(strRstVTrue, dbOpenDynaset, dbSeeChanges)
Set rstvFalse = CurrentDb.OpenRecordset(strRstVFalse, dbOpenDynaset, dbSeeChanges)
strFieldName = "txtRequirementPage"
Do While Not rstvTrue.EOF
Forms!frmMRecords.tbMRecordSubs.Pages(rstvTrue.Fields(strFieldName)).Visible = True
Loop
Do While Not rstvFalse.EOF
Forms!frmMRecords.tbMRecordSubs.Pages(rstvFalse.Fields(strFieldName)).Visible = False
Loop
End Function
If anyone can help me figure out my stupidity, you deserve an up vote, a check mark, and a cookie.
EDIT again
Below is updated code for the public function. I fixed the rs for the true query, and I added in the MoveNext for the loops.
Public Function ShowRequirements()
Dim db As DAO.Database
Dim strRstVTrue As String
Dim rstvTrue As DAO.Recordset
Dim strRstVFalse As String
Dim rstvFalse As DAO.Recordset
Dim strFieldName As String
'Setup the recordset
Set db = CurrentDb
strRstVTrue = "SELECT tblMRecordRequirements.ID, tblMRecordRequirements.FKMC, tblReqType.txtRequirementPage " & _
"FROM tblMRecordRequirements LEFT JOIN tblReqType ON tblMRecordRequirements.FKRequirementType = tblReqType.ID " & _
"WHERE tblReqType.txtRequirementPage Is Not Null AND tblMRecordRequirements.FKMC = " & Nz(Forms!frmMRecords!ID, 0)
strRstVFalse = "SELECT tblReqType.ID, tblReqType.txtRequirementPage, tblMRecordRequirements.FKMC " & _
"FROM tblReqType LEFT JOIN tblMRecordRequirements ON tblReqType.ID = tblMRecordRequirements.FKRequirementType " & _
"WHERE tblReqType.txtRequirementPage Is Not Null AND tblMRecordRequirements.FKMC <> Is Null"
Set rstvTrue = CurrentDb.OpenRecordset(strRstVTrue, dbOpenDynaset, dbSeeChanges)
Set rstvFalse = CurrentDb.OpenRecordset(strRstVFalse, dbOpenDynaset, dbSeeChanges)
strFieldName = "txtRequirementPage"
Do While Not rstvTrue.EOF
Forms!frmMRecords.tbMRecordSubs.Pages(rstvTrue.Fields(strFieldName)).Visible = True
rstvTrue.MoveNext
Loop
Do While Not rstvFalse.EOF
Forms!frmMRecords.tbMRecordSubs.Pages(rstvFalse.Fields(strFieldName)).Visible = False
rstvFalse.MoveNext
Loop
End Function
EDIT REDUX
I think I may have it worked out, but let me know what you all think. I really appreciate all your thoughts on this, as I know you all have a lot of experience not just in figuring out these kinds of challenges, but ensuring the code is good and not prone to issues.
Here is where I am at:
Public Function ShowRequirements()
Dim db As DAO.Database
Dim db2 As DAO.Database
Dim strRstVTrue As String
Dim rstvTrue As DAO.Recordset
Dim strRstVFalse As String
Dim rstvFalse As DAO.Recordset
Dim strFieldName As String
strFieldName = "txtRequirementPage"
Set db = CurrentDb
Set db2 = CurrentDb
strRstVTrue = "SELECT tblReqType.txtRequirementPage " & _
"FROM tblReqType LEFT JOIN tblMRecordRequirements ON tblMRecordRequirements.FKRequirementType = tblReqType.ID " & _
"WHERE tblReqType.txtRequirementPage Is Not Null AND tblMRecordRequirements.FKMC = " & MCID
strRstVFalse = "SELECT tblReqType.txtRequirementPage " & _
"FROM tblReqType LEFT JOIN tblMRecordRequirements ON tblMRecordRequirements.FKRequirementType = tblReqType.ID " & _
"WHERE tblMRecordRequirements.ID Not In (Select ID From [tblMRecordRequirements] WHERE [tblMRecordRequirements]![FKMC] = " & MCID & _
") AND tblReqType.txtRequirementPage Is Not Null;"
Set rstvTrue = db.OpenRecordset(strRstVTrue, dbOpenDynaset, dbSeeChanges)
Set rstvFalse = db2.OpenRecordset(strRstVFalse, dbOpenDynaset, dbSeeChanges)
Do While Not rstvTrue.EOF
Forms!frmMRecords.tbMRecordSubs.Pages(rstvTrue.Fields(strFieldName)).Visible = True
rstvTrue.MoveNext
Loop
Do While Not rstvFalse.EOF
Forms!frmMRecords.tbMRecordSubs.Pages(rstvFalse.Fields(strFieldName)).Visible = False
rstvFalse.MoveNext
Loop
End Function
I need this code to run anytime the main form is loaded, and the detail is made visible (meaning a main record has been chosen from a find form). Also anytime a requirement record is added.
Put the code you shared inside a sub procedure and call the sub procedure from Form_Load(), Form_Current(), Form_AfterInsert() event handler, etc.
As for elegance, I'd focus on maintainability and efficiency rather than looks, but concise code is also nice. 1) You can use a With block to reduce redundant object method calls, but that'll only work for one reference at a time. 2) Instead create another variable to temporarily hold a value/object from a series of dot property-accessors. 3) It looks like pages and column values are already numbered with a consistent naming pattern, so leverage that in a loop. 4) Comparison operations in VBA are largely Boolean operations, so they return True or False. The result of an entire Boolean expression can be assigned to another Boolean variable/property. (Boolean operations can also return Null... which is usually, but not always, treated like False. If you're certain that your data doesn't have Null values, then you can simplify the code and ignore this issue. If the data can contain null, then you need to adjust the code appropriately.)
Me.Parent!pgReqType1 is calling the default property of the Parent form which is Controls, which default property is Item. The bang operator ! passes the code text as a string into the collection Item method. In short, it is equivalent to Me.Parent.Controls.Item("pgReqType1").
Dim i as integer
Dim ctls as Controls
Dim reqValue as string
Set ctls = Me.Parent.Controls
reqValue = Me.FKRequirementType.Column(1)
For i = 1 to 4
ctls.Item("pgReqType" & i).Visible = (reqValue = "ReqType" & i)
Next i
About all I can do is translate the specific code snippet you show. I have the feeling there is probably more to it than this, because the code snippet you shared ensures that there will only be one tab visible: It is testing the same column value multiple times which could only have one value. Bug? Incomplete example?
This really goes against my better judgement of Stack Overflow principles --to not answer multi-part, continuing debugging questions-- but I really want a cookie.
How could the posted code have ever worked, since you are not moving through either recordset? There are no MoveNext calls. That means that both recordsets are empty or an error is being thrown that is being ignored somewhere (i.e. On Error Resume Next). Otherwise, it should lock up Access with infinite loops. Sometimes you can stop the code with Ctrl+Break, but not always successful in Access.
More precise table schema is required to properly interpret your data, but I'll make some assumptions. You state that tblReqType contains all requirement types. I'll assume that tblMRecordRequirements contains rows only for requirements which are "applied" (a.k.a. "on", "selected") for the ID value in tblMRecordRequirements.FKMC. Assuming the converse, if there are no rows in tblMRecordRequirements with ID in tblMRecordRequirements.FKMC for a given tblMRecordRequirements.FKRequirementType, then the requirement is not "applied" to that ID.
Does every row in tblReqType have a value in txtRequirementPage, or do some rows have null values? Also, can multiple requirements have the same page specified? Or is it a true one-to-one requirement-to-page mapping with no null values?
First of all why would the first query not be an INNER JOIN, since I assume that only records that match in both tables should be returned for the Visible = True condition? Depending on your answers above, this would probably make the condition tblReqType.txtRequirementPage Is Not Null unnecessary in the first query.
Simply reversing a LEFT JOIN will not return what you want especially if you select all other ID values ( tblMRecordRequirements.FKMC <> Nz(Forms!frmMRecords!ID, 0) ). All that does is give you the requirements for every other ID values. Not only will that be inefficient since it could return many, many irrelevant records, it could be likely that over all other ID values that every possible requirement would be applied, so that the second query will essentially cause all requirements to be invisible.
Further picky observations:
If Forms!frmMRecords!ID is null, then you might as well not even execute the queries. You should check that value for null separately and perform appropriate actions rather than letting that specific condition fall through the other code, even if the end side effect is what you desire. It makes the code harder to debug and interpret properly. In other words write code that does "If ID is null, set all pages to visible = false, then exit the sub (i.e. skip other code)"
It's more efficient to get a read-only snapshot rather than an fully-updatable Dynaset recordset: Too much overhead just for looping through without data manipulation.
Proper break points, debug output and error handling code can help identify bad code. It is worth tracing through results of recordsets manually to inspect values and proper SQL syntax.
Try this:
Public Sub ShowRequirements()
Dim db As DAO.Database
Dim iID As Long '? Assuming long integer
Dim strSQL As String
Dim rsTabs As DAO.Recordset
On Error Resume Next
iID = -1 '* Set to bogus value
If Not IsNull(Forms!frmMRecords!ID) Then
iID = Forms!frmMRecords!ID
End If
If iID = -1 Or Err.Number <> 0 Then
'* Problem accessing ID control on form (empty recordset, new record row, etc.)
'* or it is null
'Set all tab pages to Visible = False?
Exit Sub
End If
On Error GoTo Catch
'* Setup the recordset
Set db = CurrentDb
'* Use embedded query (replacable with saved query) for filtering on ID values.
'* This is critical so that the LEFT JOIN does not return or filter records
'* based on other ID values.
strSQL = _
"SELECT tblReqType.ID, tblReqType.txtRequirementPage, (IDReq.FKRequirementType Is Not Null) As ShowTab " & _
" FROM tblReqType LEFT JOIN" & _
" (SELECT MReq.FKRequirementType FROM tblMRecordRequirements AS MReq " & _
" WHERE MReq.FKMC = " & iID & ") AS IDReq" & _
" ON tblReqType.ID = IDReq.FKRequirementType" & _
" WHERE tblReqType.txtRequirementPage Is Not Null"
Set rsTabs = db.OpenRecordset(strRstVTrue, dbOpenSnapshot, dbReadOnly)
Do While Not rsTabs.EOF
Forms!frmMRecords.tbMRecordSubs.Pages(rsTabs!txtRequirementPage).Visible = rsTabs!ShowTab
rsTabs.MoveNext '* Advance recordset. (Avoid infinite loops.)
Loop
CloseAll:
On Error Resume Next
'* Best habit to explicitly close recordsets and database connections, even when not necessary (since they'll close automatically when they go out of scope)
If Not rsTabs Is Nothing Then
rsTabs.Close
Set rsTabs = Nothing
End If
Set db = Nothing
Exit Sub
Catch:
'* At least report error for development
Debug.Print "ShowRequirements(): Error: " & Err.Number & ": " & Err.Description
'* Show MsgBox or update form status control?
'* Set all tab pages to Visible = False?
'* Form state could be misleading without proper user notification and/or error handling
Resume CloseAll
End Sub

Access Conditional Formatting - Fewer VBA Options over user interface?

The problem is that while the front-end allows 4 or more conditions, when I tried to set conditions using VBA, I ran into an error when setting the 4th condition. In other words, if I only tried to set 3 conditions in the code, then the code worked fine.
I am using MS Access 2010. I need to set conditional formatting for two textboxes on a continuous form. I know that older versions of MS Access allowed only 3 conditions on a textbox, but I know that I can get more conditions in Access 2010. My current application has 4 conditions using the user interface. In my research on this question, one person said that later versions of MS Access allow up to 50 conditions. I could not confirm this either way, even when I reviewed the Access 2010 specifications page. But I know I can at least get more than 3 conditions.
Here is the test code that works for up to 3 records:
Function fApplyConditionFormatNow()
Dim objFormatConds As FormatCondition
Dim i As Integer 'index number for specific format conditions
Dim stSQL As String 'query to get list of categories
Dim rs As DAO.Recordset
i = 0
'clear out just in case FormatConditions accidentially got saved
'with the form at some point.
Me.ID.FormatConditions.Delete
'get a recordset containing the formatting information
'(ie, get RGB values for each category type)
stSQL = "SELECT * FROM tblTestConditionalFormatting;"
fRunSQL stSQL, rs 'fRunSQL is custom code that gets runs stSQL and returns the recordset
'loop through recordset to get conditional formatting values
Do Until rs.EOF
'create a condition on textbox named "ID". The condition will be for
'the Category/Type (TypeNm) that's up now in the recordset.
Set objFormatConds = Me.ID.FormatConditions.Add(acExpression, , "[TypeNm] = '" & rs!TypeNm & "'")
'add formatting for the condition just created.
With Me.ID.FormatConditions(i)
.BackColor = RGB(rs!RGB1, rs!RGB2, rs!RGB3)
End With
i = i + 1
rs.MoveNext
Loop
rs.Close
Set rs = Nothing
End Function
When 4 records are included in the category table : ie, tblTestConditionalFormatting, I get the following error:
"Runtime error 7966: The format condition you specified is greater than the number of format conditions."
So, there appears to be a bug in that the front-end can handle more than 3 conditions but the VBA object can only handle 3 conditions? OR maybe I'm doing something wrong. Has anyone else come across this? Do you have an idea for a work around?
Thank you!!
Instead of With Me.ID.FormatConditions(i), use the FormatCondition object that you just created:
Set objFormatConds = Me.ID.FormatConditions.Add(acExpression, , "[TypeNm] = '" & rs!TypeNm & "'")
'add formatting for the condition just created.
With objFormatConds
.BackColor = RGB(rs!RGB1, rs!RGB2, rs!RGB3)
End With
You don't need i anymore.
I have similar code that goes (simplified) like this:
For i = 1 To 6
lColor = DLookup("Color", "someTable", "p_Color_ID = " & i)
Set objFrc = txtFld.FormatConditions.Add(acExpression, , "[ColorGroup] = '" & i & "'")
objFrc.BackColor = lColor
Next i
Edit
Apparently you can edit the FormatConditions >= 3 if you don't touch 0..2:
https://access-programmers.co.uk/forums/showthread.php?t=271679
Maybe I have something like this... :/

How can I populate combo box from a database query?

I want to populate a combo box with the results of a query in Access. I'm just not seeing how to do it. As far as I understand, one must first create a record set, read the query results into the record set, then write the record set to the combo box's row source property. Is this correct? is there a simple example somewhere that I can follow? I haven't found one in any of the other threads.
Here's my attempt so far:
Dim RS As Recordset
Dim myDB As Database
Set RS = myDB.OpenRecordset("SourcesNotDisposed", dbOpenDynaset)
Do While Not RS.EOF
With Me.cmbSN
RowSource.AddItem
End With
Loop
With this code, I'm getting an "Object required" error at the RowSource line. cmbSN has data properties:
Row source Type = Table/Query
Bound Column = 0
Limit to List = Yes
Allow value list edits = Yes
Inherit value list = Yes
Show only row source = No
The query only has one visible column called "Serial Number"
Thanks in advance
Thanks for all the suggestions everyone. I've worked it out and found a very simple solution. With the combo box's Row Source Type property set to Table/Query, all I needed to do was set the Row Source property to a valid SQL string. e.g.:
strSQL = "SELECT Sources.[Serial Number] FROM Sources " & _
"WHERE (((Sources.Nuclide)='Cf-252') " & _
"AND ((Sources.[Location / Status])<>'Disposed')) " & _
"ORDER BY Sources.[Serial Number];"
Me.cmbItem.RowSource = strSQL
Me.cmbItem.Requery
Below code insert table fields into combo box. Add this code under onEnter event of combo
Private Sub CM_Enter()
'CM is combobox name
Dim strItem1 As String
Dim strItem2 As String
On Error Resume Next
Dim i As Integer 'Index for loop
With Me.CM
.RowSourceType = "Value List" 'Set rowsource type as Value list
.RowSource = "" 'Clean combo contents
End With
'Loop through field names of table and add them to your combo:
For i = 1 To CurrentDb.TableDefs("table1").Fields.Count - 1
Me.CM.AddItem (CurrentDb.TableDefs("table1").Fields(i - 1).Name)
Next i
'/***Delete unwanted items from the combo
strItem1 = "col1"
strItem2 = "col2"
'CM.RemoveItem strItem1
'CM.RemoveItem strItem2
End Sub
I think you might need to do a 'first read a record' before starting the loop.
Try using a RS.MoveFirst before the Do-While loop?
I think you may also need to do a .MoveNext inside your loop, just before the Loop statement; it's been a long while since I did anything like this in VBA, but it looks to me like it'll just add the same item over and over until it runs out of memory? I don't think the AddItem moves the record pointer to the next record by itself.
You may also need to check what happens if you MoveNext off the end of the record set...
HTH :)

vba function to return record with most recent date. given another criteria

I need to set the default value for a textbox in an ms access 2010 form. The default value needs to be the most recent date in CommunicationTable where the ClientNumber is the same as the ClientNumber associated with the current record in the form. The code below references the correct ClientNumber, but I am not sure how to get the most recent date. I am concerned that DMax might not be the appropriate function for getting the most recent date. How should I change the following to get the most recent date?
=DMax("DateOfCommunication","[CommunicationTable]","[ClientNumber]= "
& [Forms]![Main]![NavigationSubform].[Form]![ClientNumber] & "")
I realize I should also post the larger function in which the above function is nested:
=DLookUp("[Level]","[CommunicationTable]","DateOfCommunication= "
& DMax("DateOfCommunication","[CommunicationTable]","[ClientNumber]= "
& [Forms]![Main]![NavigationSubform].[Form]![ClientNumber] & ""))
Also, the form itself is bound to CommunicationTable. This VBA function is in the DefaultValue dialog box, which I get into via the property sheet for the text box. So I am not sure that creating a sql query will work in this case.
EDIT:
I have uploaded a stripped down copy of the database which reproduces the problem at this file sharing site.
To locate the code:
1.) Open the CommunicationEntryForm and
2.) open the AfterUpdate() event procedure for the ClientNumber field.
Next, to reproduce the problem:
1.) close `CommunicationEntryForm`
2.) In the Main form(which should already be open), click the View tab to open
the most recent CommunicationForm for any Client you want. Note the Level
number for that Communication.
3.) Click on the Communication tab. This will leave the form and show a list
of CommunicationForms for that Client.
4.) Click the Create New Form button. This will open up CommunicationEntryForm.
The value for Level should be the same as the value you noted in step 1 above.
The problem is that this is blank.
Can someone show me how to fix this problem?
#CodeMed - I did download the database but found you have issues other than what you are describing- such as when you 'add' a new communication you simply overwrite an existing record. I managed to get the result you were looking for, but it just changes the 3 records around. Does your non-sample program actually have the ability to create and add new records? As it is, I just changed your existing code to this:
Private Sub cmdNewCommForm_Click()
Dim cNum As Long
Dim strSQL As String
Dim rs As Recordset
Dim db As Database
Set db = CurrentDb
cNum = Forms!Main!NavigationSubform.Form!ClientNumber
strSQL = "SELECT Top 1 Co.Level AS MaxOfLevel " & _
"FROM CommunicationTable co Where Co.ClientNumber = " & cNum
Set rs = db.OpenRecordset(strSQL)
Forms!Main!NavigationSubform.Form!NavigationSubform.SourceObject = "CommunicationEntryForm"
Forms!Main!NavigationSubform.Form!NavigationSubform!ClientNumber = cNum
Forms!Main!NavigationSubform.Form!NavigationSubform!DateOfCommunication = Date
If rs.RecordCount > 0 Then
Forms!Main!NavigationSubform.Form!NavigationSubform!Level = rs!MaxOfLevel
Else
Forms!Main!NavigationSubform.Form!NavigationSubform!Level = 0
End If
Set rs = Nothing
Set db = Nothing
End Sub
What I would do is first grab the date by doing something like:
Dim db as Database
Dim rec as Recordset
Set db = CurrentDB
Set rec = db.OpenRecordset("SELECT Top 1 DateOfCommunication FROM CommunicationTable WHERE ClientNumber= " & [Forms]![Main]![NavigationSubform].[Form]![ClientNumber] & " ORDER BY DateOfCommunication DESC")
This will get the most recent date. Then, in your above VBA, you can just stick rec(0) in where your calculation was:
Me.MyDateField = DLookUp("[Level]","[CommunicationTable]","DateOfCommunication= #" & rec(0) & "#")
Substitute "MyDateField" with whatever that name of your date field actually is.
I'm pretty sure you need the pound signs (or "hashtags" as the kids call them today...) in order for Access to do the calculation on a date value.

how to limit the characters in access to more than 255

How to limit the characters in access to more than 255? for example, I want it the memo or text box to limit it to max 300 characters.
In Access 2010
If you want to limit a memo field in a table to no more than 300 characters, open the table in design view and add this as the field's Validation Rule property.
Len([memo_field])<301
Substitute your field's name for memo_field. You can also add a Validation Text property to display a more user-friendly message when the rule is violated. With no Validation Text, that rule would produce this message ... which might not be very clear to a user:
*One or more values are prohibited by the validation rule 'Len([memo_field])<301' set for 'YourTableName.memo_field'. Enter a value that the expression for this field can accept.*
You also mentioned a text box. If it is a text box bound to a memo field, you can validate the character length in the text box's Before Update event. If the text box is named txtMemo_field:
Private Sub txtMemo_field_BeforeUpdate(Cancel As Integer)
If Len(Me.txtMemo_field) > 300 Then
MsgBox "Please limit data to maximum of 300 characters."
Cancel = True
End If
End Sub
After the message box, the cursor will be still located within the text box, and the user will not be allowed to move to another form field without supplying an acceptable value for txtMemo_field.
Just to address a point in #HansUp's answer:
Is Null Or Len([memo_field])<301 ... If you don't want to allow
Nulls, drop the "Is Null Or" part.
There is no need to explicitly test for nulls in a constraint. A constraint doesn't have to evaluate TRUE for it to be satisfied.
If the Access database engine (ACE, Jet, whatever) actually had a spec it would read like this:
A table constraint is satisfied if and only if the specified
search condition is not false for any row of a table.
According to three-valued logic required to handle nulls, the search condition LEN(NULL) < 301 evaluates to UNKNOWN and the table constraint would be satisfied (because UNKNOWN is not FALSE).
However, Access has no such spec, so we must test and see that the above assertions are indeed true (simply copy and paste into any VBA module, no references required, creates a mew blank mdb in the user's temp folder, then creates table, Validation Rule -- without the explicit test for null -- then attempts to add a null with success, Q.E.D.):
Sub WhyTestIsNull()
On Error Resume Next
Kill Environ$("temp") & "\DropMe.mdb"
On Error GoTo 0
Dim cat
Set cat = CreateObject("ADOX.Catalog")
With cat
.Create _
"Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" & _
Environ$("temp") & "\DropMe.mdb"
With .ActiveConnection
Dim Sql As String
Sql = _
"CREATE TABLE Test (" & _
" ID INTEGER NOT NULL UNIQUE, " & _
" memo_field MEMO" & _
");"
.Execute Sql
End With
' Create Validation Rules
Dim jeng
Set jeng = CreateObject("JRO.JetEngine")
jeng.RefreshCache .ActiveConnection
.Tables("Test").Columns("memo_field") _
.Properties("Jet OLEDB:Column Validation Rule").Value = _
"LEN(memo_field) BETWEEN 1 AND 300"
jeng.RefreshCache .ActiveConnection
Sql = "INSERT INTO Test (ID, memo_field) VALUES (1, NULL);"
.ActiveConnection.Execute Sql
Sql = "SELECT * FROM Test;"
Dim rs
Set rs = .ActiveConnection.Execute(Sql)
MsgBox rs.GetString(2, , , , "<NULL>")
Set .ActiveConnection = Nothing
End With
End Sub
Change its Data type to Memo.
max field size of text field
Regards