Besides iterating through each item, is there way to check if layer exists?

Started by healthNut, August 11, 2012, 02:41:50 AM

Previous topic - Next topic

0 Members and 1 Guest are viewing this topic.

healthNut

I'm accessing a layer from the layers collection by name:
Set layerObj = layersObj( "layerNameStr")
This crashes when layerNameStr item does not exist

I seen the for loop through each item to check if it exists but that seems inefficient
There's gotta be a better ways
-catch the error?
-layer.exist function?

aledlund

There are several places where assigning an object (i.e. layer, shape, etc.) can return 'nothing' or 'null'. Good programming will wrap these in some form of error catching. Example in .Net is try...catch..end try or in VBA 'on error goto something'. Remember when you build these mini-handlers to point your code back to the main handler when completed.

al


on error goto layerErrHandler
set layerObj = layersObj("layerNameStr")
layerErrHandler:
if layerObj is Nothing then
    ' go do something because you couldn't find it
end if
on error goto mainErrHandler

....

al

healthNut

Thanks, took your advice and error caught. Would appreciate help on the handling part though:
How do I Negate the "Is" operator? In other words, what's the VBA equivalent for != in C++?

I  have a getLayer function that returns nothing if the layer does not exist.
-Set layerObj = getLayer(layersObj, strSpecialty)

Then checking if nothing is returned
-If Nothing Is layerObj Then
which works fine

What if I want to negate it? I tried
-If Nothing <> layerObj and
-If Nothing Is Not layerObj
but get compilation errors of type mismatch.
What I got works, just looking for logical understanding.

aledlund

you might try

if Not (layerObj Is Nothing) then
end if


if layerObj is Nothing then
  ' did not find the layer
else
  ' found the layer
end if

this is of interest to know

http://www.tek-tips.com/faqs.cfm?fid=3710

al



Visio Guy

I use a lot of "loop-scanners" in my code, because reading from Visio is quite fast. I don't like using Try-Catch for things like layers or shapes, since they can execute quite slowly if the error condition pops up.

I think it depends on if your code is expecting something or not. If you are trying to get a layer, and you expect it to be there 99.5% of the time, then a try-catch is in order.

If you are going to prompt the user to create a layer if it's not there, and it might very likely not exist, you should probably scan to see if it exists. Even 50 layers will be read very quickly (especially in relation to any user interaction that might follow) so it won't hurt to loop through them.
For articles, tips and free content, see the Visio Guy Website at http://www.visguy.com
Get my Visio Book! Using Microsoft Visio 2010

healthNut

Cool, thanks for the tips. Had no idea, looping would be faster but I did notice that error handling does take time.