|< Day Day Up >|
In your code, the method ZoomTimescale requires some object to act upon:
If nothing is selected, Project does not know how to set the timescale .
One way to fix this is to make the macro a bit more intelligent than it currently is. Using the car example again, you can see that if the car could be made to test the existence of the road ahead before it accelerated, it could prevent itself from driving off a cliff. You can do a similar thing in code by using a basic test. The object that you want to test is Selection . Here is the code you use to test it:
Sub ZoomSelected() If Not ActiveSelection.Tasks(1) Is Nothing Then ZoomTimescale Selection:=True End If End Sub
The line If Not ActiveSelection.Tasks(1) Is Nothing Then tests to see if there is a valid selection. If there is a selection, the ZoomTimescale() method is executed. If there is not a selection, you do nothing.
Fine-tuning the Macro and Giving User Feedback with Message Boxes
If a user runs the macro when nothing is selected, nothing happens and the user doesn't know why nothing happened. You can improve that by telling the user what happened . The easiest way to do this is to pop up a message box that tells what happened (see Figure 3). To do this, you simply add two lines of code, as shown here:
Sub ZoomSelected() If Not ActiveSelection.Tasks(1) Is Nothing Then ZoomTimescale Selection:=True 'add the following two lines Else MsgBox ("No Tasks Selected") End If End Sub
Figure 3. The message box displays whatever text you have specified within brackets.
Another way to make your code friendlier is to anticipate what choice the user would make if what he or she is trying to do is unsuccessful . In this case, you can simply zoom to show the entire project. Be careful about what you assume. It is wiser to do nothing and tell the user that than to do the wrong thing. The following code illustrates the change:
Sub ZoomSelected() If Not ActiveSelection.Tasks(1) Is Nothing Then ZoomTimescale Selection:=True 'add the following two lines Else MsgBox ("No Tasks Selected") ZoomTimescale Entire:=True End If End Sub
It is best to record a macro when the objects and actions you are using will be the same every time. The following are some activities that fall into this category:
However, you can also record macros in order to figure out how to write code to do other things you want to do. You can use the code that the macro recorder develops as building blocks to construct more complicated macros.
|< Day Day Up >|