Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the distinction between a CommandButton's .caption and .text properties in VBA?

Tags:

excel

vba

I have a CommandButton in Excel and found that both the .Caption and .Text properties return the same visible text of the button. Here's the code I used to see the values:

Debug.Print ActiveSheet.Buttons("My_Command_Button").Caption
Debug.Print ActiveSheet.Buttons("My_Command_Button").Text

What is the distinction between these two properties and does the distinction matter?

like image 310
ChrisB Avatar asked Sep 08 '18 01:09

ChrisB


1 Answers

Trick question. If you examine the CommandButton coclass definition in fm20.dll (or in the VBE's Object Browser, you'll find that it doesn't have a Text property:

CommandButton in Object Browser

The ActiveX controls are composited via extension at run-time, so properties that are specific to how the control is embedded in a spreadsheet, or a UserForm, (or anything else for that matter) are actually being driven by the OLE container that "owns" the object. It makes a certain amount of sense if you think about it - why should a CommandButton care what it's Left or Top property is? You shouldn't ever need to have a CommandButton that isn't the child of another parent window or container, and it isn't the responsibility of the CommandButton to determine where it is within the window - that's the window's job. It's part of the reason why they don't have public constructors:

Dim example As CommandButton
Set example = New CommandButton     '<-- Nope.

If you were able to instantiate a parentless CommandButton, you'd find that the only way to set the text on the button would be to set the .Caption property. That's because at a deep down Windows API level, it is a window (in that it has an hWnd), and the convention is for windows to have a Caption property. How that is displayed is implementation specific. In this specific instance, they can be treated interchangeably, but the .Caption property is the "real one", and the .Text property mirrors it. Unless you're doing something extremely bizarre with it (like getting its hWnd and using that with the Windows API directly), they are for all intents and purposes the same thing.

like image 180
Comintern Avatar answered Nov 14 '22 07:11

Comintern