Microsoft Access Code Samples

Also: Proper Syntax for Certain Tasks

home
Sunday, November 04, 2001 09:56:45
Topics:
  1. Syntax With Subforms, Including Changing Recordsource, Filters, Deleting Records
  2. Code for Running External Application Within Access
  3. Code for Adding Records, Deleting Records, Opening Form in Add Mode
  4. Code for Hiding Window, Restoring, Maximizing
  5. Searching Records Using SQL Statements Rather Than Queries
  6. Closing Forms, Opening Forms (Basic Code Naturally), Dis-allowing Edits or Allowing Edits on the Form
  7. Checking for Nulls
  8. MsgBox Yes/No Format
  9. DLookup Format
  10. Update Queries, Running Within Visual Basic
  11. Removing Drop-Down Menu When Displaying a Form

Syntax with Subforms

Plug Values from Main Form Into Subform


'(sfrCoursesInClass) is the CONTROL name that the subform has within the main form
Me.sfrCoursesInClass.Form.[class_name] = Me.Course
' Go to the subform
Me![sfrInstructorsInClass].SetFocus
' Go the specific text box in the subform
Me![sfrInstructorsInClass].Form![instructor_name].SetFocus
7/30/01 1:37:32 PM

Plug Entry from Main Form Into Subform

05-24-2010
Syntax
Me.subform_control_name.Form.[subform_field_name]=Me.main_form_field_name

Example
Me.sfrmIncidents.Form.[st_type] = Me.Type

Change RECORDSOURCE of a Subform

Assume you have a subform browse_form located in a main form. The subform is recognized by the "control" name browse_subsheet within the main form. To change its RECORDSOURCE:

Me![browse_subsheet].Form.RecordSource = sSQL

Pluck Value from a Subform to Use

Assume the same above example, and that you want to pluck the "autoid" and "mold_number" fields from the subform. The syntax:

Dim stID As Integer, stMoldNumber As Integer
stID = Me.browse_subsheet.Form!autoid
stMoldNumber = Me.browse_subsheet.Form!mold_number

Change RECORDSOURCE of a Combo Box Programatically

sSQL="Select"....
Me.store_name.RowSource=sSQL

Quote Marks Issue

If you are trying to set a variable equal to quote marks, or include quote marks inside the string, """" is the syntax which Access 97 recognizes as quotation marks. The easiest method is to set aside a variable equal to this value, and include it in later expressions to represent the quote marks.

So, say, if you're trying to set a variable equal to "c:program files" "h:\file.txt" use the following syntax (the important parts are bolded:

Dim stQuotemark as string, stFilepath as String
stQuotemark=""""
stFilepath = stQuotemark & "c:program files" & stQuotemark & " " & stQuotemark & "h:\file.txt" _
& stQuotemark

Open Form

Dim stDocName As String
Dim stLinkCriteria As String
Dim StatusBox As String
stDocName = "browse_form"
DoCmd.OpenForm stDocName, , , stLinkCriteria
Commonly, though, you don't need all the above. (If you use the "wizard" to generate code, it tends to look like the above.) Rather, you can commonly do just this:
DoCmd.OpenForm "browse_form"

Open Search Form after Clicking "Go"

Using SQL Encoding, Allows Multiple Criteria & Eliminates Need For Regular Queries
Makes the SQL Code the RECORDSOURCE of the form Opens up the Form Using the SQL Code as Criteria
dim sSQL as String, stQuotemark As String
stQuotemark = """"
' sSQL derived from Query which shows all values from "Main Query" and filters out by packlist number ONLY
sSQL = "SELECT main_query.* FROM main_query WHERE (((main_query.packlist) Like " _
& stQuotemark & "*" & stQuotemark & " & [Forms]![search_form]![packlist_entered] & " _
& stQuotemark & "*" & stQuotemark & "));"
DoCmd.OpenForm "browse_form"
Forms![browse_form]!StatusBox = "You Searched for Packlist Number " & Forms![search_form]!packlist_entered _
& ". Results....."
Forms![browse_form].Form.RecordSource = sSQL
dim sSQL as String, stQuotemark As String
stQuotemark = """"
' sSQL derived from Query which shows all values from "Main Query" and filters out by packlist number ONLY
sSQL = "SELECT main_query.* FROM main_query WHERE (((main_query.packlist) Like " _
& stQuotemark & "*" & stQuotemark & " & [Forms]![search_form]![packlist_entered] & " _
& stQuotemark & "*" & stQuotemark & "));"
DoCmd.OpenForm "browse_form",,sSQL
Forms![browse_form]!StatusBox = "You Searched for Packlist Number " & Forms![search_form]!packlist_entered _
& ". Results....."

For more specifics on using SQL in Visual Basic Code to limit recordsets, go to the section How to Filter a Form/Search Records By More Than 1 Criteria, and Reduce "Query Clutter

Note: the "_" character is used to break up long lines into several shorter lines. Make sure each line ENDS as " _"

Also, the method which applies the SQL as a "RECORDSOURCE" works better if, say, you will then have a report which inherits the RECORDSOURCE of the form to generate its reports.

Using Normal Queries rather than SQL statements
To Use as Criteria for Opening the Form:
DoCmd.OpenForm "browse_form", acNormal, "search_packlist_query"
Forms![browse_form]!StatusBox = "You Searched for Packlist Number" _
& " " & [Forms]![search_form]![packlist_entered] _
& " " & ". Results...."
To Apply the Query as a Filter to the Form
DoCmd.OpenForm "browse_form"
With CodeContextObject
DoCmd.ApplyFilter "search_packlist_query", ""
Forms![browse_form]!StatusBox = "You Searched for Packlist Number" _
& " " & [Forms]![search_form]![packlist_entered] _
& " " & ". Results...."
End With

Button to Open a Form & Add New Record

DoCmd.OpenForm "main_ship_form", acNormal, "", "", acAdd, acNormal
DoCmd.GoToControl "ship_to"

Or, to create a button on the form itself to add a new record on the current form:

DoCmd.GoToRecord , , acNewRec

Proper Syntax to Use in Search Query (Which Allows "Harris" to find "Harrison")

Like "*" & [Forms]![search_form]![packlist_entered] & "*"

Code Samples for Specifying Filters on a Form

Subform
Private Sub id_sd_AfterUpdate()
Forms!main_form!tolerances_subform.Form.Filter = "[part_id] = " & Forms!main_form!autoid & " AND [ip_sd] = " & (Me!id_sd = "In Process")
Forms!main_form!tolerances_subform.Form.FilterOn = True
End Sub
Single Form
Private Sub Command43_Click()
Dim stQt As String
stQt = """"
DoCmd.OpenForm "browse_all_form", , ""
Forms![browse_all_form]!StatusBox = "You Searched for Packlist Number"
Forms![browse_all_form].Form.Filter = "[part_number] = " & stQt & "60735" & stQt
Forms![browse_all_form].Form.FilterOn = True
End Sub

Running an External Application from Within Access

Sample 1
' If the file the user is looking for is 60080_02, for example, the filepath to run it would be
'c:\Program Files\Adobe\Acrobat 4.0\Reader\AcroRd32.exe "p:\Released Drawings-PDF\60080_02.pdf"
Dim stAppName As String, QuoteMark As String
QuoteMark = """"
stAppName = "c:\Program Files\Adobe\Acrobat 4.0\Reader\AcroRd32.exe" _
& " " & QuoteMark & "p:\Released Drawings-PDF\" & Forms![mold_form_main]!drawing_number _
& "_" & Forms![mold_form_main]!revision_number & ".pdf" & QuoteMark
Call Shell(stAppName, 1)
Sample 2
QuoteMark = """"
stAppName = "c:\winnt\explorer.exe" _
& " " & QuoteMark & "p:\Released Drawings-PDF\" & QuoteMark
Call Shell(stAppName, 1)

Sample Code for Making A Main Form Search By "Part Number" (in This Example)

5/16/01

Note: This Code is sample code which doesn't actually work properly. It's here simply for archiving persons for the future.

This is useful for making a data-entry form look for, say, the part number you are entering when entering a new entry. This helps make sure that (in this example) the part number you are assigning to a new entry does not already belong to an older entry. It pulls up the record if it already exists.

This code is flawed, however, because it still adds a new "blank" entry to the table in the event that a pre-existing record with that part number comes up. This is because it adds a new entry (and assigned an "autoid" value) BEFORE performing this check. The last 3 lines at the bottom are an attempt to start addressing this, but this code at this point needs work. It is NOT final.

Private Sub Part_Number_AfterUpdate()
Dim strTempSSN As String
strTempSSN = Me.Part_Number
Me.RecordsetClone.FindFirst "[part_number]= " & Chr(34) & strTempSSN & Chr(34)
If Me.RecordsetClone.NoMatch Then
 MsgBox "You are Entering a New Part Number for a New Record."
Me.Part_Number = strTempSSN
With CodeContextObject
.AllowAdditions = True
.AllowDeletions = True
End With
DoCmd.GoToRecord , , acNewRec
Me.Part_Number = strTempSSN
Else
 Me.Part_Number = Me.swp_value
 Me.Bookmark = Me.RecordsetClone.Bookmark
End If
End Sub


Private Sub Part_Number_Enter()
Me.swp_value = Me.Part_Number
End Sub

Perhaps a better alternative is to set up the form to search for duplicates and flash a warning message if the value you enter is a duplicate. Go here to read how to do this.

How to Hide/Close/Minimize (etc) a Window in Visual Basic

DoCmd.RunCommand acCmdWindowHide

You can also minimize, maximize, or restore the window with the following code samples:

DoCmd.Maximize

DoCmd.Restore

DoCmd.Minimize

Or, the CLOSE the window, the following code will do it, and do so without causing error messages:

DoCmd.Close acForm, "search_form"

Allow Edits Property

Form.AllowEdits = False

Checking for Null Values on a Form

6/28/01 3:12:55 PM

The methods for specifying for (or checking for) null values on a form is a bit unorthodox. Here are some samples of how to do this (the 1st line DOES work, not sure about the other ones; they were suggested to me from newsgroup readers):

If IsNull(Me.location)
If Me.location & "" = ""
If (Nz(Me!Location_Entered,"")="") Then

"Giving Focus" To A Report

7/16/01 10:53:17 AM

The code for making a report receive the focus is not the same as it is for a form. The following code will do it:

DoCmd.SelectObject acReport, "NameOfYourReport"

Conditional Formatting/Sensing the Active Control

Screen.ActiveControl.Name
Me.ActiveControl.BackColor = vbBlue
Me.ActiveControl.ForeColor = vbYellow

Code for Deleting Records

7/26/01 10:10:31 AM

These code samples are UNTESTED, I have simply put them here as reference since I am currently trying to figure them out:

DoCmd.RunCommand acCmdSelectRecord
DoCmd.RunCommand acCmdDeleteRecord
Or,....
 Me.recordsetclone.bookmark=me.bookmark
 Me.recordsetclone.delete
DoCmd.RunSQL "Delete * from log_table WHERE log_table.autoid = " & Forms!main_form![log_form]![autoid]

Moving, Rezing Controls Programatically

8/17/01 11:15:23 AM
The Original, Less-Preferred Way:
Private Sub show_hide_button_Click()
If Me.tab_control.Visible = True Then
Me.tab_control.Visible = False
Me.browse_subsheet.Height = 9999
With Me.show_hide_button
.Caption = "Shrink"
End With
Else
Me.tab_control.Visible = True
Me.browse_subsheet.Height = 3000
With Me.show_hide_button
.Caption = "Grow"
End With
End If
End Sub

I received this suggestion at a newsgroup regarding this issue: (microsoft.public.access.formscoding 8-16-01 11:20 am)

You should really use relative terms not absolute values:

grow = 2000
browse_subsheet.Height = browse_subsheet.Height + grow
browse_subsheet.Top = browse_subsheet.Top - grow / 2
The "Better" Way Which I Later Learned
8/20/01 8:48:47 AM

Based on the above statements, I generated the following code, which I like better:

If purchase_req_sub_form.Height = 1920 Then
purchase_req_sub_form.Height = purchase_req_sub_form.Height + 3000
Else
purchase_req_sub_form.Height = 1920
End If

I noticed that the height numbers in Visual Basic don't correspond to the units in inches expressed in the properties sheet. I extracted the unit of the "normal" size with code similar to the following:

MsgBox "The Height Is " & purchase_req_sub_form.Height

Message Box Format

MsgBox "You Don't Have Permission to Modify the Contents of this Record; You Weren't The One Who Created it.", , "Permissions Violation"


message = "There is a record with packlist number " & Me.packlist & " in the tooling database. Do you want " _
& "to pluck in those values?"
response = MsgBox(message, vbYesNo, "From Larry...")
If response = vbNo Then
Resume Exit_Command43_Click 'this will cancel the Exit

Dim response As Integer, message As String
message = "The REQUESTED BY field cannot contain a null value. Do you wish to enter a value " _
& "right now? (You don't have to do so to save this record successfully, but the field is " _
& "still a required field)?"
If IsNull(Me.requested_by) Then
response = MsgBox(message, vbYesNo, "OOPS!")
If response = vbYes Then
Cancel = True 'this will cancel the Exit

Update Queries Running Within Visual Basic

sSQL = "UPDATE tbl_ticksheet SET tbl_ticksheet.linked_to_keycode_log_table = True WHERE case_number = " & Me.autoid
CurrentDb.Execute sSQL
sSQL = "UPDATE tbl_ticksheet SET tbl_ticksheet.source = " & stQuote & Me.ticksheet_source_cbox & stQuote & "WHERE case_number = " & Me.autoid
CurrentDb.Execute sSQL

You can also Go Here For More Information

DLookup Syntax

Me.keycode = DLookup("[keycode]", "tbl_key_codes", "[product] = " & strQuote & Me.product & strQuote & "AND [used] = NO")

Removing Drop-Down Menu When Displaying a Form

  1. Open the form in DESIGN view
  2. Under the "other" tab, in the "menu bar" row, enter =1.

Input Mask Within Visual Basic


Me.regstration_number.InputMask = "000\-00\-0000;;_"