Access Objects, Properties and Methods

Home | EXCEL VB Programming (XL97-2003) | ACCESS Programming | EXCEL VB.Net Programming | EXCEL Spreadsheet Functions
Material  Management | Master Scheduling & Production Planning | Forecasting Methods & Techniques | About Me |
Guestbook
 


Access Programming
Access Database basic
Objects, Collections, Properties and Methods
DoCmd Objects
Forms, Control and Events
ADO (ActiveX Data Objects)
ADO examples
ADOX (ADO Extensions)
ADOX examples
Jet SQL (Structured Query Language)
Jet SQL examples
String manipulation
Integrating Access/Excel
Access 2003 VBA Constants
 
   
Examples of Access's objects, properties and methods

Access database is made up of different kinds of Objects, such as tables, queries, forms, reports, modules, macros, data access pages, as well as components of those objects (such as Fields and Index objects in a Tables object). Another example is like the controls (list box, combo box, textbox, etc) of a Form object. Some objects are used to display the data, while others are used to store and manage the data itself, or to assist you in Visual Basic programming.

The things that an object know what to do are called Methods. An object can have 3 types of Properties - read/write, read-only, and write-only. Most properties can be set at design time and modified at runtime; but however, there are some which can't be modified at runtime, and others can't be accessed at design time. How can you determine this? To see this clearly, select an object and view its property sheet [see example here]. One quick way to understand all the properties and methods associated with a particular object is to invoke Help or press F1. In the Help topics dialog box, type the object name or simply click to select the particular object [see example]. Another way is go to the Object Browser, click the particular object in the classes and you will see all its associated members (properties, methods ands) in the right pane [see example].

On top of Access Object Model is the Application object, which refers to the active Access application, and it contains Access's other objects and collections. The Reference object refers to a reference set to another application's or project's type library. The Modules object gives you control over the VBA modules in your database. The CurrentProject object lets you access and manipulate the application components of your database, whereas the CurrentData object let you reference the data elements of the underlying database engine. The DoCmd object provide you access to all actions in Access, and it consists only of methods. The Forms object refers to a particular Access form, each Forms object has a Controls collection, which contains all controls on the form. A Report object refers to a particular Microsoft Access report. The Screen object to refer to the active object on the screen.

Figure 1.0  Access Object Model [Access 2003]
Application
CurrentData
AllDatabaseDiagrams―AccessObject
AllFunctions―AccessObject
AllQueries―AccessObject
AllStoredProcedures―AccessObject
AllTables―AccessObject
AllViews―AccessObject

CurrentProject
AccessObjectProperties―AccessObjectProperty
AllDataAccessPages―AccessObject
AllForms―AccessObject
AllMacros―AccessObject
AllModules―AccessObject
AllReports―
AccessObject

DoCmd
Forms
Form
Control
Controls
Module
Properties
Section
Modules
Module
References
Reports
Report
Control
Controls
GroupLevel
Module
Properties
Section

Screen
Control
Form
Pages
Properties
Report


The following provides the description of the objects.

Objects

Description

Application The active Access application.
Reference Reference to an application’s object library.
CurrentData The objects stored in the current database by the source application (Jet or SQL).
CurrentProject The project for the current Access project (.adp) or Access database (.mdb).
DoCmd Macro actions used in VBA code.
Forms Open form, including subforms.
Modules Open standard module or class module.
Reports Open report, including subreports.
Screen Screen that currently has the focus.

 

Create VBA objects in code

Although you can create some objects through Access's user interface, but most VBA objects can only be created in code. The following code creates an instance of the Orders form in the Northwind database, and display it with a message. See diagram. By default, new forms are hidden when they are created. The Visible property is set to True, so that the form is visible onscreen. After you click OK, the form will be hidden.

Sub CreateObject()
' declare the object variable 'frm', of the Form_Orders type.
Dim frm As Form_Orders
' to instantiate the class (i.e. to create a new instance of the Form_Orders class, and use the variable frm to refer to that object).
Set frm = New Form_Orders
frm.Visible = True
MsgBox "Click OK"
End Sub

' or alternatively, you can write with just one line:  Dim variablename as New classname which both declares and
instantiate the variable.

Dim frm As New Form_Orders

Note:
The class itself is not an object. Making an object from a class is called instantiating the class, and one class can instantiate many objects. Also, when you declare and instantiate an object variable in one statement, the object is not created until the first time that you use that object variable in code.


Setting Values to Properties

A property is an attribute of an object. An object can have none or more than one properties. Some objects share the same properties but at other times, an object's properties are specific to that particular object only. When instantiating an object from a class, each of these properties has a value. You can use VBA code to read or assign new values to these properties. The example below turns on the form's Visible property and RecordSelectors property. You can either print, display or assign the values of the properties to variables.

Dim frm As New Form_Orders
frm.Visible = True
frm.RecordSelectors = True


Invoking Methods


Methods are actions that an object takes on itself. A method is specific to the object it applies to. For example, a form has a Repaint method (completes any pending screen updates/recalculations for a specified form) that does not apply to a combo box. Below is an example of SetFocus method that applies to combo box.

Private Sub CmdButton_Click()
' Check to see if a value is entered into the CustomerID combo box.
 If IsNull(Me.cboCustomerID) Or Me.cboCustomerID = "" Then
   MsgBox "You must enter a Customer ID", vbOKOnly, "Required Data"
   Me.cboCustomerID.SetFocus
   Exit Sub
 End If
End Sub



Understanding Collections

Collections are sets of objects of the same type; they contain all their respective objects in the entire database. Think of object as a member of a collection. For example, frmOrders is a form that is a member of the Forms collection; cmdPrintInvoice, a command button on frmOrders, is a member of the Controls collection of the form frmOrders. Do not confuse Forms collection with the list of all the forms in your database; that list belongs to part of the CurrentProject object.

Below is an example that has each iteration of the loop, retrieve the name of the currently open objects in the Forms collection.

Sub ListObjects1()
' to instantiate by setting object variable to each member of the Forms collection.
Dim frmOrders As New Form_Orders
Dim frmProducts As New Form_Products
' to open the forms.
frmOrders.Visible = True
frmProducts.Visible = True

' iterate through the Forms collection to list out the name of the forms that are currently open.
Dim frm As Form
  For Each frm In Forms
      Debug.Print frm.Name
  Next frm
End Sub


This second example illustrates the two methods of looping through other members of the collections, then print every control name of the open forms, name of all the open Modules and the open Reports.


Sub ListObjects2()
' declare the object variables.
Dim ctl As Control, frm As Form, rpt As Report, mdl As Modules
Dim i As Integer
Set mdl = Application.Modules
  For Each frm In Forms
      Debug.Print frm.Name
      For Each ctl In frm.Controls
            Debug.Print " " & ctl.Name
      Next ctl
  Next frm
  Debug.Print "Reports"

  For Each rpt In Reports
      Debug.Print " " & rpt.Name
  Next i
  Debug.Print "Modules"

  For i = 0 To mdl.Count - 1
      Debug.Print " " & mdl(i).Name
  Next i
End Sub

 

CurrentProject object

It returns a reference to the current database. It contains properties such as Name, Path, and Connection. It also contains collections (AllForms, AllMacros, AllModules, AllReports, and AllDataAccessPages). These collections are used to iterate through all the classes of objects in the database. They differs from Forms, Macros, Modules, etc, in that they refer to all objects stored in the current project, rather than just to open them. For instance, the AllForms collection collection contains all the saved forms that make up your database; whereas the Forms collection comprises only the forms currently running in memory or open. These collections contain AccessObject objects as shown in figure 1.0. For example, the AllForms collection contains one AccessObject for each form in the current database.

Example: to check whether a form exists or not in the current database. To evaluate the function, for example, enter this in the immediate window: ?DoesFormExist ("Orders")

Function DoesFormExist(frmName As String) As Boolean
   On Error GoTo HandleErr   
' if attempt fails, it goes to error-handler.
   Dim acObj As AccessObject
   Set
acObj = CurrentProject.AllForms(frmName)
   DoesFormExist = True  
' if the form exists, VBA returns True.
ExitHere:
   Exit Function
HandleErr:
   DoesFormExist = False  
' if the form doesn't exists, VBA returns True.
   Exit Function
End Function

 

Example: to list out all the forms and macros that make up your database.

Sub CurrentProjectObject()
With CurrentProject
  
' print out name and path of the current project.
   Debug.Print .Name
   Debug.Print .Path

  
' loop through every form and macro in the current project, and print out their names.
   Dim f As Variant, m As Variant
   For Each f In .AllForms
      Debug.Print " " & f.Name
   Next f

   For Each m In .AllMacros
      Debug.Print " " & m.Name
   Next m
End With
End Sub

Go To Top

List of Access Methods
Methods:
AccessError DDERequest hWndAccessApp Remove
Add DDETerminate HyperlinkPart RemoveItem
AddFromFile DDETerminateAll ImportXML Rename
AddFromGuid DefaultWorkspaceClone InsertLines Repaint
AddFromString Delete InsertText RepaintObject
AddItem DeleteControl IsDependentUpon ReplaceLine
AddMenu DeleteLines Item Requery
AddToFavorites DeleteObject Line Restore
ApplyFilter DeleteReportControl LoadPicture Run
ApplyTheme DFirst Maximize RunCommand
Beep DLast Minimize RunMacro
BuildCriteria DLookup Modify RunSQL
CancelEvent DMax Move Save
Circle DMin MoveSize Scale
Close DoMenuItem NewAccessProject SelectObject
CloseConnection Dropdown NewCurrentDatabase SendObject
CloseCurrentDatabase DStDev Nz SetDefaultWorkgroupFile
CodeDb DStDevP OpenAccessProject SetFocus
CompactRepair DSum OpenConnection SetHiddenAttribute
ConvertAccessProject DVar OpenCurrentDatabase SetMenuItem
CopyDatabaseFile DVarP OpenDataAccessPage SetOption
CopyObject Echo OpenDiagram SetWarnings
CreateAccessProject EuroConvert OpenForm ShowAllRecords
CreateAdditionalData Eval OpenFunction ShowToolbar
CreateControl Execute OpenModule SizeToFit
CreateEventProc ExportXML OpenQuery StringFromGUID
CreateForm Find OpenReport SysCmd
CreateGroupLevel FindNext OpenStoredProcedure TextHeight
CreateNewDocument FindRecord OpenTable TextWidth
CreateNewWorkgroupFile Follow OpenView TransferDatabase
CreateReport FollowHyperlink OutputTo TransferSpreadsheet
CreateReportControl GetDependencyInfo Print TransferSQLDatabase
CurrentDb GetHiddenAttribute PrintOut TransferText
CurrentUser GetOption PSet TransformXML
DAvg GoToControl Quit Undo
DCount GoToPage Recalc UpdateDependencyInfo
DDEExecute GoToRecord Refresh UseDefaultFolderSuffix
DDEInitiate GUIDFromString RefreshDatabaseWindow  
DDEPoke Hourglass RefreshTitleBar  

 

Go To Top

List of Access Properties

Properties:

About DatasheetBorderLineStyle Kind PivotTableChange
AccessConnection DatasheetCellsEffect LabelAlign PopUp
Action DatasheetFontHeight LabelX Port
ActiveControl DatasheetFontItalic LabelY PostalAddress
ActiveDataAccessPage DatasheetFontName LanguageSettings PreviousControl
ActiveDatasheet DatasheetFontUnderline LayoutForPrint PrintCount
ActiveForm DatasheetFontWeight Left Printer
ActiveReport DatasheetForeColor LeftMargin Printers
AddColon DatasheetGridlinesBehavior LimitToList PrintQuality
Address DatasheetGridlinesColor Lines PrintSection
AfterDelConfirm DateCreated LineSlant ProcBodyLine
AfterFinalRender DateGrouping LineSpacing ProcCountLines
AfterInsert DateModified LinkChildFields ProcOfLine
AfterLayout DBEngine LinkMasterFields ProcStartLine
AfterRender DecimalPlaces ListCount ProductCode
AfterUpdate Default ListIndex ProjectType
AllDataAccessPages DefaultControl ListRows Properties
AllDatabaseDiagrams DefaultSize ListWidth PrtDevMode
AllForms DefaultValue LocationOfComponents PrtDevNames
AllFunctions DefaultView Locked PrtMip
AllMacros DefaultWebOptions LpOleObject Query
AllModules Dependants MailEnvelope ReadingOrder
AllowAdditions Dependencies Major RecordLocks
AllowAutoCorrect DeviceName MaxRecButton RecordSelectors
AllowDatasheetView Dirty MaxRecords Recordset
AllowDeletions DisplayAutoCorrectOptions MenuBar RecordsetClone
AllowDesignChanges DisplayType MinMaxButtons RecordsetType
AllowEdits DisplayWhen Minor RecordSource
AllowFilters DividingLines Modal RecordSourceQualifier
AllowFormView DoCmd Module References
AllowPivotChartView Document Modules RepeatSection
AllowPivotTableView DownloadComponents MousePointer Report
AllQueries DrawMode MouseWheel Reports
AllReports DrawStyle Moveable ResyncCommand
AllStoredProcedures DrawWidth MoveLayout RightMargin
AllTables DriverName MSODSC RowHeight
AllViews Duplex MultiRow RowSource
AnswerWizard EmailSubject MultiSelect RowSourceType
Application Enabled Name RowSpacing
AsianLineBreak Encoding NavigationButtons RunningSum
Assistant EnterKeyBehavior NewFileTaskPane ScaleHeight
AutoActivate EventProcPrefix NewRecord ScaleLeft
AutoCenter Expression1 NewRowOrCol ScaleMode
AutoCorrect Expression2 NextRecord ScaleTop
AutoExpand FastLaserPrinting NumeralShapes ScaleWidth
AutoLabel FeatureInstall Object Scaling
AutomationSecurity FetchDefaults ObjectPalette Screen
AutoRepeat FileDialog ObjectVerbs ScreenTip
AutoResize FileFormat ObjectVerbsCount ScrollBarAlign
AutoTab FileSearch OldBorderStyle ScrollBars
BackColor FillColor OldValue Section
BackStyle FillStyle OLEClass Selected
BaseConnectionString Filter OLEType SelectionChange
BeforeDelConfirm FilterLookup OLETypeAllowed SelHeight
BeforeInsert FilterOn OnActivate SelLeft
BeforeQuery FolderSuffix OnApplyFilter SelLength
BeforeRender FollowedHyperlinkColor OnChange SelStart
BeforeScreenTip FontBold OnClick SelText
BeforeUpdate FontItalic OnClose SelTop
Bookmark FontName OnConnect SelWidth
BorderColor FontSize OnCurrent ServerFilter
BorderStyle FontUnderline OnDblClick ServerFilterByForm
BorderWidth FontWeight OnDeactivate Shape
BottomMargin ForceNewPage OnDelete ShortcutMenu
BoundColumn ForeColor OnDirty ShortcutMenuBar
BrokenReference Form OnDisconnect SizeMode
Build Format OnEnter SmartTagActions
BuiltIn FormatConditions OnError SmartTags
Cancel FormatCount OnExit SortOrder
CanGrow Forms OnFilter SourceDoc
CanShrink FrozenColumns OnFormat SourceItem
Caption FullName OnGotFocus SourceObject
ChartSpace FullPath OnInsert SpecialEffect
Class FuriganaControl OnKeyDown StatusBarText
CloseButton GridX OnKeyPress Style
CodeContextObject GridY OnKeyUp SubAddress
CodeData GroupFooter OnLoad SubdatasheetExpanded
CodeProject GroupHeader OnLostFocus SubdatasheetHeight
Collection GroupInterval OnMenu TabFixedHeight
ColorMode GroupLevel OnMouseDown TabFixedWidth
Column GroupOn OnMouseMove TabIndex
ColumnCount GrpKeepTogether OnMouseUp TabStop
ColumnHeads Guid OnNoData Tag
ColumnHidden HasContinued OnNotInList TargetBrowser
ColumnOrder HasData OnOpen Text
ColumnSpacing HasModule OnPage TextAlign
ColumnWidth Height OnPrint TextToDisplay
ColumnWidths HelpContextId OnPush TimerInterval
COMAddIns HelpFile OnResize Toolbar
CommandBars HideDuplicates OnRetreat Top
CommandBeforeExecute Hwnd OnTimer TopMargin
CommandChecked Hyperlink OnUndo Transparent
CommandEnabled HyperlinkAddress OnUnload TripleState
CommandExecute HyperlinkColor OnUpdated Type
Connection HyperlinkSubAddress OpenArgs UnderlineHyperlinks
ConnectionString ImageHeight Operator UniqueTable
ControlBox ImageWidth OptionValue UnsupportedObjects
Controls IMEHold OrderBy UpdateOptions
ControlSource IMEMode OrderByOn UseDefaultPrinter
ControlTipText IMESentenceMode OrganizeInFolder UseLongFileNames
ControlType InputMask Orientation UserControl
Copies InputParameters OutOfDateObjects ValidationRule
Count InSelection Page ValidationText
CountOfDeclarationLines InsideHeight PageFooter Value
CountOfLines InsideWidth PageHeader VBE
CurrentData InsufficientPermissions PageIndex Verb
CurrentObjectName IsBroken Pages Version
CurrentObjectType IsCompiled Painting Vertical
CurrentProject IsConnected PaintPalette ViewChange
CurrentRecord IsHyperlink PaletteSource ViewsAllowed
CurrentSectionLeft IsLoaded PaperBin Visible
CurrentSectionTop IsMissing PaperSize WebOptions
CurrentView IsVisible Parent WhatsThisButton
CurrentX Item Path Width
CurrentY ItemData Picture WillContinue
Custom ItemLayout PictureAlignment WindowHeight
Cycle ItemsAcross PictureData WindowLeft
DataAccessPages ItemSizeHeight PicturePages WindowTop
DataChange ItemSizeWidth PicturePalette WindowWidth
DataEntry ItemsSelected PictureSizeMode XML
DataOnly KeepTogether PictureTiling  
DataSetChange KeyboardLanguage PictureType  
DatasheetBackColor KeyPreview PivotTable  
 


Go To Top

AddItem Method

A
dds a new item to the list of values displayed by the specified list box control or combo box control. The RowSourceType property of the specified control must be set to "Value List". This method is only valid for list box or combo box controls on forms. List item numbers start from zero. O the opposite, you use the RemoveItem method to remove items from the list of values.

expression.AddItem(Item, Index)

Item - required string, the display text for the new item.
Index - optional, the position of the item in the list. If omitted, the item is added to the end of the list.

   Example: to adds an item to the beginning of the list in a combo box control.

Function AddItemToBeginning(ctrlComboBox As ComboBox, ByVal strItem As String)
    ctrlComboBox.AddItem Item:=strItem, Index:=0
End Function

Example: to loop through all tables in the current database adding the name of each table to the list box.

Dim obj As AccessObject
For Each obj In CurrentData.AllTables
    Me.lstTables.AddItem obj.Name
Next obj

Go To Top

DLookup function
To get the value of a particular field from a specified set of records (a domain). Use the function in Visual Basic, a macro, a query expression, or a calculated control on a form or report.

DLookup(expr, domain, [criteria])

expr      – An expression that identifies the field whose value you want to return. It can be a string expression identifying a field in a table or query, or it can be an expression that performs a calculation on data in that field . In expr, you can include the name of a field in a table, a control on a form, a constant, or a function. If expr includes a function, it can be either built-in or user-defined, but not another domain aggregate or SQL aggregate function.
domain A string expression identifying the set of records that constitutes the domain. It can be a table name or a query name for a query that does not require a parameter.
criteria  An optional string expression used to restrict the range of data on which the DLookup function is performed. For example, criteria is often equivalent to the WHERE clause in an SQL expression, without the word WHERE. If criteria is omitted, the DLookup function evaluates expr against the entire domain. Any field that is included in criteria must also be a field in domain; otherwise, the DLookup function returns a Null.

Examples.
DLookup("FieldName" , "TableName" , "Criteria = n")       ' for numerical values
DLookup("FieldName" , "TableName" , "Criteria= 'string'")    
' for strings
DLookup("FieldName" , "TableName" , "Criteria= #date#")   
' for dates

' Refering to form's control
DLookup("FieldName", "TableName", "Criteria = " & forms!FormName!ControlName)     
' for numerical values
DLookup("FieldName", "TableName", "Criteria = '" & forms!FormName!ControlName & "'")    
' for strings
DLookup("FieldName", "TableName", "Criteria = #" & forms!FormName!ControlName & "#")  
' for dates
DLookup("FieldName", "TableName", "Criteria1 = " & Forms!FormName!Control1 _   
    ' for mixed criteria
& " AND Criteria2 = '" & Forms!FormName!Control2

Examples:
' To look up ProductName from a Products table based on the value in the text box.
' Create another text box and set its ControlSource property to the following expression.

=DLookup("[ProductName]", "tblProducts", "[txtProductID] =" & Forms![Order Details]!ProductID)

Go To Top

Move method
It moves the specified object to the coordinates specified by the argument values. The 4 arguments refer to the screen position in twips for the 4 edges of the object relative to the 4 edges of the Access window. The last 3 arguments of the syntax below are optional.

expression.Move(Left, Top, Width, Height)

Example: to determines whether or not the first form in the current project can be moved; if it can, the code will move the form.  

If Forms(0).Moveable Then
    Forms(0).Move 0, 0, 300, 500  
' or use,  Left:=0, Top:=0, Width:=300, Height:=500
Else
    MsgBox "The form cannot be moved."
End If

Go To Top

MoveSize method
Let you change the position and size of the object that currently has the focus. The units for the arguments are twips. You must include at least one argument.

expression.MoveSize(Right, Down, Width, Height)

Example:
Private Sub Form_Load()
' to open the form larger than its original condensed size.
DoCmd.MoveSize ,  , 9000, 5678
End Sub

Go To Top

Refresh method
Refresh method immediately updates the records in the underlying record source for a specified form or datasheet to reflect changes made to the data by you and other users in a multiuser environment. It's often faster to refresh a form or datasheet than to requery it. Don't confuse the Refresh method with the Repaint method, which repaints the screen with any pending visual changes.

Example:
Private Sub Form_Activate()
    ' to change the recordsource of this form that is activated.
    Me.RecordSource = "Qry_SalesQ3"
    Me.Refresh
End Sub

Go To Top


Repaint method
It completes any pending screen updates for a specified form. When performed on a form, the Repaint method also completes any pending recalculations of the form's controls. Do not confuse Repaint method with the Echo method - the Repaint method forces a single immediate repaint, while the Echo method turns repainting on or off.

Example:
Private Sub Form_Activate()
    Me.Repaint
End Sub

Go To Top

RemoveItem Method
Removes an item from the list of values displayed by the specified list box control or combo box control.Only valid for list box or combo box controls on forms. RowSourceType property of the control must be set to "Value List".

Example: to remove the specified item from the list in a list box control.
Function RemoveListItem(ctrlListBox As ListBox, ByVal varItm As Variant) As Boolean
   On Error GoTo ERROR_HANDLER

  
' Remove the list box item and set the return value to True, indicating success.
   ctrlListBox.RemoveItem Index:=varItm
   RemoveListItem = True

  
' Reset the error trap and exit the function.
   On Error GoTo 0
   Exit Function

' Return False if an error occurs.
ERROR_HANDLER:
   RemoveListItem = False
End Function

Go To Top

SetFocus method
Moves the focus to the specified form, the specified control on the active form, or the specified field on the active datasheet.

Example:
' use the SetFocus method to move the focus to a txtCustomerID textbox on a Customers form.
Private Sub Form_Open(Cancel As Integer)
   
Forms!Customers!txtCustomerID.SetFocus     ' or use Me!txtCustomerID.SetFocus
End Sub

Go To Top

DataEntry property
Used to specify whether a bound form opens to allow data entry only. It doesn't determine whether records can be added; it only determines whether existing records are displayed. Read/write Boolean. True means the form opens showing only a blank record; False (Default) means the form opens showing existing records.

Example:
Private Sub Form_Load()
  
' if the form is loaded in DataEntry mode, and the OpenArgs argument is not null, set txtOrderID textbox
   ' equal to the opening argument.
   If Me.DataEntry And Not (IsNull(Me.OpenArgs)) Then
      Me.txtOrderID = Me.OpenArgs
   End If
End Sub

Go To Top

IsLoaded property
Used to determine if an AccessObject is currently loaded. Read-only Boolean.

Example: after adding new value, to unload the form if it is still loaded  
Private Sub cboOrderID_NotInList(NewData As String, Response As Integer)
   ' open the frmOrder form in add mode, passing in the new data
   DoCmd.OpenForm "frmOrders", _
   DataMode:=acFormAdd, WindowMode:=acDialog, OpenArgs:=NewData

   ' If form is still loaded, unload it
   If IsLoaded("frmOrder") Then
       Response = acDataErrAdded
       DoCmd.Close acForm, "
frmOrder"
   Else
       Response = acDataErrContinue
   End If
End Sub

Go To Top

ControlSource property
You can use the ControlSource property to specify what data appears in a control. You can display and edit data bound to a field in a table, query, or SQL statement. You can also display the result of an expression. You can set the ControlSource property for a text box by typing a field name or expression directly in the text box in form Design view

The ControlSource property uses the following settings:
fieldname - The control is bound to a field in a table, query, or SQL statement. Data from the field is displayed in the control. Changes to the data inside the control change the corresponding data in the field.
expression - The control displays data generated by an expression. This data can be changed by the user but isn't saved in the database.

Examples.
' this sets the ControlSource property for a text box named txtCustomers to a field named CustomersID
Forms!Customers!txtCustomers.ControlSource = "CustomersID"

' this sets the ControlSource property for a text box named RequiedDate to the expression that displays a date ten days from today in the control.
Me
!RequiedDate.ControlSource = "=Date() + 10"

Go To Top

ColumnHeads property
Display a single row of column headings for list boxes, combo boxes, and OLE objects that accept column headings.
Note: Headings in combo boxes appear only when displaying the list in the control.

Example: click the check box to display column headings in the list box.
' to bound the check box's control 'txtHead' to list box's MultiSelect control, to display column headings
Private Sub txtHead_AfterUpdate()
Me.lstMultiSelect.ColumnHeads = Me.txtHead
End Sub

Go To Top

Column property
Refer to a specific column, or column and row combination, in a multiple-column combo box or list box. Use 0 to refer to the first column, 1 to refer to the second column, and so on. You can use the Column property to assign the contents of a combo box or list box to another control, such as a text box.

expression.Column(Index, Row)

Index - required, a long integer that can range from 0 to the setting of the ColumnCount property minus one.
Row - optional variant - an integer that can range from 0 to the setting of the ListCount property minus 1.

Examples.
' to refer to list box's control SelectCategory in the 2nd column & 3rd row, of the form SalesReportsDialog.
Forms!
SalesReportsDialog!SelectCategory.Column(1, 2)

' to set the ControlSource property of a text box to the value in the 2nd column of a list box.
=Forms!
SalesReportsDialog!SelectCategory.Column(1)

Go To Top

ColumnCount property
U
sed to specify the number of columns displayed in a list box or in the list box portion of a combo box, or sent to OLE objects in a chart control or unbound object frame. The property holds an integer between 1 and the maximum number of fields in the table, query, or SQL statement, or the maximum number of values in the value list, specified in the RowSource property of the control.

For table fields , you can set this property on the Lookup tab in the Field Properties section of table Design view for fields with the DisplayControl property set to Combo Box or List Box.

Example: a generic code using the Column property and the ColumnCount property to print the values of a list box selection.
Sub Read_ListBoxSelection()
    Dim intNumColumns As Integer
    Dim intI As Integer
    Dim frmCust As Form

    Set frmCust = Forms!frmCustomers
    If frmCust!lstCustomerNames.ItemsSelected.Count > 0 Then

       
' Any selection?
        intNumColumns = frmCust!lstCustomerNames.ColumnCount
        Debug.Print "The list box contains "; intNumColumns; _
            IIf(intNumColumns = 1, " column", " columns"); " of data."
        Debug.Print "The current selection contains:"
        For intI = 0 To intNumColumns - 1
           
' Print column data.
            Debug.Print frmCust!lstCustomerNames.Column(intI)
        Next intI
    Else
        Debug.Print "You haven't selected an entry in the " & "list box."
    End If
    Set frmCust = Nothing
End Sub

Go To Top

BoundColumn property
When you make a selection from a list box or combo box, the BoundColumn property tells Access which column's values to use as the value of the control. If the control is bound to a field, the value in the column specified by the BoundColumn property is stored in the field named in the ControlSource property.

expression.BoundColumn

Note:
■ In VB code, set the BoundColumn property by using a number equal to a value from 0 to the setting of the ColumnCount property.
■ If BoundColumn property is set to 1, you can access the value stored in that column by using the expression Column(0). Remember BoundColumn property uses 1-based numbers to refer to the columns, whereas Column property uses zero-based numbers to refer to columns.

Example: to refer to the BoundColumn property, you can use the column property.
' Column(0) refers to the first column as column property is zero-based.
Me.ControlName = Me.ComboBoxName.Column(0)

Go To Top

Item property
A default property of the Forms collection, it returns a specific member of a collection either by position or by index. The index argument must be a number from 0 to the value of the collection's Count property minus 1.

Example: to iterate through the built-in Forms collection to list out the name of the forms.  
' declare a variable i to act as loop counter
Dim i As Integer

' set the loop from 0 to the number of open forms -1
For i = 0 To Forms.Count - 1
    Debug.Print Forms.Item(i).Name     ' or simply,  Forms(i).Name as Item is the default property
Next i

Go To Top

ItemData property
Returns the data in the bound column for the selected row(s) in a combo box or list box. You can iterate through the ItemsSelected collection to determine which row or rows in the list box have been selected, and use the ItemData property to return the data in those rows. The list box's MultiSelect property must be set to Simple or Extended to enable the user to select more than one row at a time.

expression.ItemData(index)

expression - required, returns objects of either ComboBox Object, Control Object, or ListBox Object.
index - required Long. The row in the combo box or list box containing the data you want to return. Rows in combo box and list box are indexed starting with zero.

Example: LostFocus event is triggered to show warning message when there is not at least one item selected.
Private Sub lstCustomers_LostFocus()
    Dim varItm As Variant, lst As Access.ListBox

    Set lst = lstCustomers
    ' check for at least one selected item
    If lst.ItemsSelected.Count = 0 Then
        MsgBox "Please select a customer", vbOKOnly, "Error"
        Exit Sub
    End If

    ' cycle through selected items and deselect selected items
    For Each varItm In lst.ItemsSelected
       
MsgBox lst.ItemData(varItm)
        lst.Selected(varItm) = 0    '
deselect each of the selected items
    Next varItm
End Sub

Go To Top

ItemsSelected property
It return a read-only reference to the hidden ItemsSelected collection. This hidden collection can be used to access data in the selected rows of a multiselect list box control. This property applies to Control Object and ListBox Object. Use the ItemsSelected collection in conjunction with the Column property or the ItemData property to retrieve data from selected rows in a list box or combo box.

Example: to show the value of the bound column for each selected row in the list box 'SelectCategory'.
Set the list box's BoundColumn property as desired and its MultiSelect property to Simple or Extended for both the 2 examples.

Sub BoundData()
   Dim frm As Form, ctl As Control, varItm As Variant

    ' return Control object variable pointing to list box.
   Set frm = Forms!SalesReportsDialog
   Set ctl = frm!SelectCategory    
' or set directly as Forms!SalesReportsDialog!SelectCategory

  
' loop through each of the items in the ItemsSelected collection.
   For Each varItm In ctl.ItemsSelected
       MsgBox ctl.ItemData(varItm)
   Next varItm
End Sub


Example: to show the values of each column for each selected row in
the SelectCategory list box, instead of only the values in the bound column.

Sub AllSelectedData()
   Dim frm As Form, ctl As Control
   Dim varItm As Variant, i As Integer

   Set frm = Forms!SalesReportsDialog
   Set ctl = frm!SelectCategory
   For Each varItm In ctl.ItemsSelected
      ' enumerate through selected items.
       For i = 0 To ctl.ColumnCount - 1
           MsgBox ctl.Column(i, varItm)   
  ' display value of bound column.
       Next i
   Next varItm
End Sub

Go To Top

ListCount property
Used to determine the number of rows in a list box or the list box portion of a combo box. If you set the ColumnHeads property to Yes, the row of column headings is included in the number of rows returned by the ListCount property. You can use the ListCount property with the ListRows property to specify how many rows you want to display in the list box portion of a combo box.

Example: to find the number of rows in the list box portion of the CustomerList combo box on a Customers form.

Public Sub lstcount_CustomerList()
    Dim ListControl As Control
    Set ListControl = Forms!Customers!CustomerList
    With ListControl
        If .ListCount < 8 Then
            .ListRows = .ListCount
        Else
            .ListRows = 8
        End If
    End With
End Sub

Example: to undo the items selection in a combo box or list box's controls

Private Sub cmdUndo_Click()
    Dim i As Integer

    ' Loop through each of the items in the
list box's controls.
    For i = 0 To Me![lstMultiSelect].ListCount - 1
        Me![lstMultiSelect].Selected(i) = False
    Next i
End Sub

Go To Top

ListIndex property
Determine which item is selected in a list box or combo box. ListIndex property is an integer from 0 (first row) to the total number of items in a list box or combo box minus 1.

Example.
' to return the value of the ListIndex property
Dim l As Long
l = Forms(formname).Controls(controlname).
ListIndex

' sets the ListIndex property value.
Forms(formname).Controls(controlname).SetFocus
Forms(formname).Controls(controlname).ListIndex =
index

Go To Top

NewRecord property
Used to determine whether the current record is a new record. Read-only Integer. True means current record is new; False means the current record isn't new.

Example:
Private Sub Form_Current()
   ' if user is on a new record, move the focus to the CustomerName control.
   If Me.NewRecord Then
       Me.txtCustomerName.SetFocus
   End If
End Sub

Go To Top

OpenArgs property
OpenArgs argument applies to both the DoCmd.OpenForm method and the Form property. It returns the string expression specified by the OpenArgs argument of the OpenForm method. OpenArgs property gives you a way to pass information to a form as it is being opened.

Below is a simple example of the OpenArgs argument that passes an arbitrary data to a text box control. In the property sheet, name the text box control as txtOpenArgs. The Me keyword refers to the form itself, or form that has this code. Take note that to set most properties of a control, the control must receive the focus.

Example: to pass arguments to the control using OpenArgs property.

Private Sub Form_Load()
    txtOpenArgs.SetFocus   ' to make the textbox control as the active control.
    txtOpenArgs.Value = Me.OpenArgs
End Sub

Now run the code below from the immediate window, and you will see that the text box will display the value "I am William" that I specified in the OpenArgs argument.
DoCmd.OpenForm "Form1", , , , acFormAdd, acDialog, OpenArgs:="I am William"

Go To Top

Moveable property
It determines whether the user can move the specified form window by dragging the form by its title bar.

Example: to determines whether or not the first form in the current project can be moved.  

 
If Forms(0).Moveable Then
    Forms(0).Move 0, 0, 300, 500
Else
   
MsgBox "The form cannot be moved."
End If

Go To Top

MultiSelect property
Applies to list box only, specify whether user can make multiple selections in a list box on a form and how the multiple selections can be made. The property uses either of the following settings:

Setting VB

Description

None 0 (Default) Multiple selection isn't allowed.
Simple 1 Multiple items are selected or deselected by clicking them with the mouse or pressing the Spacebar.
Extended 2 Multiple items are selected by holding down SHIFT and clicking them with the mouse or by holding down SHIFT and pressing an arrow key to extend the selection from the previously selected item to the current item. You can also select items by dragging with the mouse. Holding down CTRL and clicking an item selects or deselects that item.

Example: To return the value of the MultiSelect property for a list box named "SelectCategory" on the "SalesReportsDialog" form
Dim b As Byte
b = Forms("SalesReportsDialog").Controls("
SelectCategory").MultiSelect
b = 2   
' MultiSelect property is set to Extended. 

Go To Top

RowSourceType &  RowSource properties
Instruct Access how to provide data to a list box, a combo box, or an unbound OLE object such as a chart. For example, to display rows of data in a list box from a query named CustomerList, set the list box's RowSourceType property to Table/Query and its RowSource property to the query named CustomerList.

■ Row Source Type ― specify whether the list is based on a table/query, a list of values, or a list of table or query field names.
■ Row Source ― depends on Row Source Type setting to determine the data type displayed by the control.

There are three types of Row Source Type settings:
■ when Row Source Type is Table/Query, Row Source settings must be a table, query or SQL statement. [see diagrams].
■ when Row Source Type is Value List, Row Source settings must be an explicit list of items separated by semicolons. [see diagram]
■ when Row Source Type is Field List, Row Source settings must be a table, query or SQL statement.

Example:
Private Sub Form_Open(Cancel As Integer)
   cboSearch.RowSourceType = "Table/Query"
   cboSearch.RowSource = "tblCustomers"
   cboSearch.ColumnCount = 2    
' specify the number of columns displayed in the combo box.
   cboSearch.ColumnWidths = "0.5 in;1 in"  
' in inches or centimeters, depending on system setting.
End Sub

 

RowSourceType Property (User-Defined Function)
This VBA UDF you create must accept five arguments. The first argument must be declared as a control and the remaining arguments as Variants. The function itself must return a Variant.

Function functionname (fld As Control, id As Variant, row As Variant, col As Variant, code As Variant) As Variant

The Function procedure has the following five required arguments.
fld    – A control variable that refers to the list box or combo box being filled.
id     – A unique value that identifies the control being filled. This is useful when you want to use the same user-defined function for more than one list box or combo box and must distinguish between them. (The example sets this variable to the value of the Timer function.)
row   – The row being filled (zero-based).
col    – The column being filled (zero-based).
code – An intrinsic constant that specifies the kind of information being requested.

Note: Because Microsoft Access calls a UDF several times to insert items into a list, often you must preserve information from call to call. The best way to do this is to use
Static variables.

Code argument can use the following intrinsic constants.
Constant Meaning  Function returns  
acLBInitialize  Initialize Nonzero if the function can fill the list; False (0) or Null otherwise.  
acLBOpen Open Nonzero ID value if the function can fill the list; False or Null otherwise.  
acLBGetRowCount Number of rows Number of rows in the list (can be zero); –1 if unknown.  
acLBGetColumnCount  Number of columns Number of columns in the list (can't be zero); must match the property sheet value.  
acLBGetColumnWidth  Column width Width (in twips) of the column specified by the col argument; –1 to use the default width.  
acLBGetValue List entry List entry to be displayed in the row and column specified by the row and col arguments.  
acLBGetFormat Format string Format string to be used to format the list entry displayed in the row and column specified by the row and col arguments; –1 to use the default format.  
acLBEnd End (the last call to a UDF always uses this value) Nothing.  
acLBClose (Not used) Not used.  
       

■ Access calls your UDF once for acLBInitialize, acLBOpen, acLBGetRowCount, and acLBGetColumnCount. It initializes the UDF, opens the query, and determines the number of rows and columns.
■ Access calls your UDF twice for acLBGetColumnWidth— once to determine the total width of the list box or combo box and a second time to set the column width.
■ The number of times your UDF is called for acLBGetValue and acLBGetFormat to get list entries and to format strings varies depending on the number of entries, the user's scrolling, and other factors.
■ Access calls your UDF for acLBEnd when the form is closed or each time the list box or combo box is queried.
■ Whenever a particular value (such as the number of columns) is required, returning Null or any invalid value causes Access to stop calling the UDF with that code.

   Explanation:
CallBack user-defined function uses DAO prior to Access2002; it was then needed to pass back certain parameters to Access about how many columns and rows of data, type of data, there are in the combo box or list box. You reference this UDF in the control's Row Source Type property. see the
diagram.

Example: when you open the form in Form view, list box then calls the CallBack function, needed by Access. The CurrentProject.AllForms.Count statement counts the number of rows and columns in the control; CurrentProject.AllForms(row).Name statement retrieves the names of all documents in the Forms collection. Access then uses this info to populate the combo or list box.


Here is this
sample database.

' You need to make reference to DAO 3.x library
Function CallbackList(ctrl As Control, id As Variant, _
row As Variant, col As Variant, code As Variant) As Variant
    Select Case code
        Case acLBInitialize  
' Initialize database.
             CallbackList = 1
        Case acLBOpen      
' Open.
             CallbackList = 1
        Case acLBGetRowCount   
' Number of rows.
             CallbackList = CurrentProject.AllForms.Count
        Case acLBGetColumnCount
    ' Number of columns.
             CallbackList = 1
        Case acLBGetColumnWidth 
  ' Column width.
             CallbackList = -1              
' Use the default width.
        Case acLBGetValue              
' Get the data.
             CallbackList = CurrentProject.AllForms(row).Name
        Case acLBGetFormat
             CallbackList = -1
    End Select
End Function

Here is another example using the Callback function to populate the list box with a list of all the tables and queries in your current database. UDF and code provided that allows you to select a table or query, to send the updated data to an Excel spreadsheet.
[ download sample ]

Go To Top

RecordSource property
To specify the source of the data for a form or report. RecordSource property setting can be a table name, a query name, or an SQL statement. For example, you can use the following settings.

Setting

Description

tblOrders a table as data source.
SELECT tblOrders!RequireDate
FROM tblOrders;
an SQL statement specifying the RequireDate field on the tblOrders table as the source of data. You can bind a control on the form or report to the RequireDate field in the tblOrders by setting the control's ControlSource property to RequireDate.

Example:
' this sets the form 'frmCustomers' RecordSource property to the table 'tblCustomers'.
Forms!frmCustomers.RecordSource = "tblCustomers"

' this sets an active form's RecordSource property to a query name.
Me.RecordSource = "qryCustOrders"

' this next example changes a form's record source to a single record in the tblCustomers table, depending on the company name selected in the cboCompanyName combo box control. The combo box is filled by an SQL statement that returns the customerID (in the bound column) and the company name. The CustomerID has a Text data type.
Sub cmboCompanyName_AfterUpdate()
    Dim strNewRecord As String
    strNewRecord = "SELECT * FROM Customers
        & " WHERE CustomerID = ' "Me!cmboCompanyName.Value & " ' "
    Me.RecordSource = strNewRecord
End Sub

Go To Top

Tag property
Stores extra information about a form, report, data access page, section, or control.

Example: this sets the controls to yellow background when you enter them.

Sub HighlightControl(ctl As Control)
    ' Set the background color of the specified control to yellow
    On Error Resume Next
    If Not IsNull(ctl.Tag) Then
         ctl.BackColor = ctl.Tag
    Else
         ctl.BackColor = 65535
    End If
End Sub


Example: this clears the highlights on all command buttons and restores the original forecolors that were saved in the Tag properties.

Function ResetCmdButtonHighlights(frm)
    Dim cntl As Control, fm As Form
    Set fm = Forms(frm)
    For Each cntl In fm.Controls
         If cntl.ControlType = acCommandButton And cntl.Tag <> "" Then
              cntl.ForeColor = cntl.Tag
              cntl.Tag = ""
        End If
    Next
    Set fm = Nothing
End Function

Go To Top

   




This site was created in February 2007
by William Tan