Outlook 2007 CommandBarControl.Execute won't work
I re开发者_StackOverflow社区cently switched to Outlook 2007 and noticed that my VBA-macros won't work. I use the following code to open a new appointment-item (and fill it automatically). It worked perfect in Outlook 2003, but now the objCB.Execute just does nothing. I tried different control IDs and it only works for some, but I could not figure out why or why not for all.
Dim ex As Explorer
Set ex = Application.ActiveExplorer
If ex.CurrentFolder.DefaultItemType <> olAppointmentItem Then
Set ex = Nothing
Exit Sub
End If
Dim objCB As CommandBarButton
Dim objAppt As AppointmentItem
Set objCB = ex.CommandBars.FindControl(, 1106)
If objCB Is Nothing Then Exit Sub
objCB.Execute
Security is set to lowest level.
In Office 2007 you will find that not every Control ID will run via CommandBar.ExecuteMSO, despite being included in the published lists. I have found that complex controls like Shape Galleries will never work but even some more simple ones have been left out for no apparent reason.
I have successfully worked around this using SendKey (inside VBA) or AutoIT (when SendKey is not enough) and selecting the control via keystrokes and sometimes mouse-clicks as necessary.
This response is not about VBA, in my recent investigation of this problem in general I have no reason to suspect it would not work. I am leaving this answer as a reference. Please take it or leave it as you will. Here is a topic on the issue as outlookcode.com.
This works fine here (I am using C#3/NET35/NET4/Outlook2007)
Before blaming the OOM right away on this issue I would first ensure that the issue is really indeed with the Execute call and not with the FindControl or other program flow. Also remember that these CommandBars can be affected by the use and/or other add-ins: manually view the tree (OutlookSpy or by code) to clear up any doubt. Also, I am unsure how VB handles implicit casts, as with the assignment. Make sure it isn't silently swallowing up an error condition.
// working C# as "proof"
int NEW_APPOINTMENT_ID = 1106;
var _button = commandBars.FindControl(Office.MsoControlType.msoControlButton,
NEW_APPOINTMENT_ID, null, false);
try {
// button is of type Office.Core.CommandBarControl or null
if (_button != null) {
_button.Execute();
};
} finally {
Util.ComRelease(ref _button); // My util, but you get the point
}
Make sure to Com-Release buttons -- Just like Items, do not rely on the RCW to take care of the references manually. It is easy to crash the add-in this way.
精彩评论