Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inconsistent behavior for Me keyword

Tags:

ms-word

vba

I noticed the behavior of Me keyword in VBA code in template files is different depending if the document has ActiveX controls or not.

  • Document with ActiveX controls: Me references the new file created from template.
  • Document without ActiveX controls: Me references the template instead of the new file.

To demonstrate this strange behavior I made two sample files:

  • WithActiveX.dotm
  • WithoutActiveX.dotm

Both files are identical, the only difference between them is that one has a Button and the other doesn't. The VBA code of both files is the following:

Private Sub Document_New()
    Selection.TypeText "Me keyword is referencing """ & Me.Name & """."
End Sub

If you create a new file from these templates, you'll realize the results are different:

WithActiveX.dotm content is

Me keyword is referencing "Document1". <-- string generated by the code above

while WithoutActiveX.dotm content is

Me keyword is referencing "WithoutActiveX.dotm". <-- string generated by the code above

I made several tests to conclude that the source of the inconsistency is the presence of ActiveX controls (there is no code associated with the control: it is merely present in the document).

Is this something by design or just a bug?

EDIT 2017-06-13: The bug described here appear to be partially fixed, but it is still reproducible. Now it happens only if there is an instance of Word opened BEFORE you create a new document using one of these templates (like a blank document).

like image 464
Diego Queiroz Avatar asked Jul 14 '13 20:07

Diego Queiroz


1 Answers

That is a bug.

According to MSDN:

Me provides a way to refer to the specific instance of the class where the code is executing.

To me this means that it should always be the new document. Ensure that you aren't running the code in the template by accident.

SOURCE: https://msdn.microsoft.com/en-us/vba/language-reference-vba/articles/me-keyword

like image 81
HackSlash Avatar answered Sep 22 '22 02:09

HackSlash