Ji Zhou ¨C MSFT
KAMACI wrote: |
Private Sub AddToolbar() Try
commandBar = Me.CommandBars("Test") 'FIRST
Catch ex As ArgumentException ' Toolbar named Test does not exist so we should create it. End Try If commandBar Is Nothing Then commandBar = Application.CommandBars.Add("Test", 1, False, True) 'SECOND End If Try
At the line of FIRST:Itgive me error.Error is: CommandBars is not a member of 'wordAddin1.ThisAddin'.I changed 'Me' keyword and rewrite that line: commandBar = Application.CommandBars("Test").(When i do this my program runs and don't give me an error while debugging)Is this an appropriate way to solve the problem and for which purpose we use CommandBars method If i make that line a command line (i mean if i write ' commandBar = Application.CommandBars("Test") )
| |
Yes, that is the appropriate way.
The article on MSDN takes VSTO document-level project as example. Document-level project's root class is ThisDocument, so Me stands for the document. The document has a CommandBars property(same as Application's CommandBars).
You are working with a Word AddIn, the root class is ThisAddIn, so Me stands for the add in's instance, you must use the Application property to access the CommandBars.
Your codes are totally right!
KAMACI wrote: |
The last thing i want to learn is that: On the SECOND line if commandBar is nothing how we can use "Add" method without "initializing" commandBar
| |
The above codes first try to get a CommandBar instance named "Test".
If commandBar is nothing, which proves that the "Test" CommandBar is still not created. So we use CommandBars.Add() method to create a CommandBar, and this method returns an instance of newly added CommandBar which we assigned to commandBar variable.
If commandBar is no nothing, which proves there is already a CommandBar named "Test", then we do not need to create it for a second time
Thanks
Ji