문제

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