In Visio VBA (or COM API)

How can i get a shape without expecting an exception when the shape name is not found?

... in my visio page, there might or might not be a Rectangle Shape with the name "DraftText".

i want to check that it is there and if yes, do smth.

my code seems like:

Shape waterMarkRect = page.Shapes["DraftText"];
if (waterMarkRect == null)
{
   waterMarkRect = page.DrawRectangle(0, 0, 50, 15);
   waterMarkRect.Name = "DraftText";
   waterMarkRect.NameU = waterMarkRect.Name;
   waterMarkRect.Text = "INCONSISTANT";

   Layer wMarkLayer = page.Layers["WMark"] ?? page.Layers.Add("WMark");
   wMarkLayer.Add(waterMarkRect, 0);
}
...
...

The problem is that, if the shape "DraftText" is not there, i get a COM Exception.

as i am against using try catch block as a coding utility,

i am searching for a way to check for the shape existance prior to taking it such as IDictionary.TryGetValue(, out);

or if(page.Shapes.Contain("DraftText"))...

Any Ideas?

有帮助吗?

解决方案

Using try catch block

Shape waterMarkRect = null;
try { 
    waterMarkRect = page.Shapes["DraftText"];
}
catch (Exception){
}

if (waterMarkRect == null)
{
   waterMarkRect = page.DrawRectangle(0, 0, 50, 15);
   waterMarkRect.Name = "DraftText";
   waterMarkRect.NameU = waterMarkRect.Name;
   waterMarkRect.Text = "INCONSISTANT";

   Layer wMarkLayer = page.Layers["WMark"] ?? page.Layers.Add("WMark");
   wMarkLayer.Add(waterMarkRect, 0);
}

其他提示

Doing it through VBA, I just do a "on error resume next" before attempting to get the shape by name, and on error goto PROC_ERR to resume error handling afterward.

If you can't disable the exception, you could loop over every shape and check its name against the one you're looking for. This would take a lot longer to perform compared with the built-in lookup by name, though.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top