Return to VBA Code Examples

Access VBA Me

In this tutorial, we will learn how to use the Me keyword in VBA.

The Me keyword in VBA can be used in place of the parent object.  This can be used in forms and worksheets in Excel, forms and documents in Word and forms and reports in Access.

Using Me in User Forms

We can use the Me keyword within the CBF (Code behind Forms) in userforms.

VBAMe UserForm_Cancel

Or within the form code itself, it could be used to refer to the parent object of each control.

To refer to Salary text box we  can use this line of code:

Me.txtSalary

and to then refer to the optLow option button, we can use this line of code:

Me.optLow

VBAMe CBF

Using Me to refer to Excel Worksheets

Me can be used to replace the name of object it is referring to in the code.  These can be used in the Event procedures of the Worksheet – such as the Worksheet_Activate procedure.

Me.Range("A10").Select

where Me refers to the Active Sheet.

Therefore in the Worksheet Activate event, the code example below would move the mouse pointer to cell A10 as soon as the user clicks on the sheet that contains this code.

VBAMe WorksheetActivate

 

Using Me to refer to Word Documents

Similarly in Word, the Me keyword can be used to reference the current word document and can be used in the event procedures of that document.

For example, it can be used in the Close event procedure of a document where it can save the document as the document closes.

VBAMe Save

 

Using Me in Access VBA

In addition to using the Me keyword to refer to the active/current form, we can also use it to refer to the active/current report.   It can also be used as part of the syntax, to refer to controls on the active form or report.

Let’s say we have a form called BasicForm, with a textbox called txtOne and a button. We would like to change the background color of the textbox on the form when the button on the form is clicked.

The code we would normally use with the full syntax is:

Forms!BasicForm![txtOne].BackStyle = 1
Forms!BasicForm![txtOne].BackColor = vbGreen

Instead of using the full syntax to refer to the form we can use the Me keyword:

Me.txtOne.BackStyle = 1
Me.txtOne.BackColor = vbGreen

Or

Me!txtOne.BackStyle = 1
Me!txtOne.BackColor = vbGreen

The result is:

Using the Me keyword in Access VBA

Note: You can use either the . or ! notation in conjunction with the Me keyword where appropriate.