使用 Excel 生成 Visio 图表 - 在 IF 语句中使用 'select' 方法

Using Excel to generate a Visio diagram - using 'select' method in IF statement

我目前正在将 Excel 与 Visio 集成,以图表方式自动填充某些元素。到目前为止,我已经完成了这项工作,但在文档、宏录制和实际做我想做的事情之间卡住了。

通过录制宏,我找到了一种 selecting 单个元素的方法,如下所示: ActiveWindow.Select Application.ActiveWindow.Page.Shapes.ItemFromID(216), visSelect

我的脚本中有一个循环如下:

For Each oItem In vsoDocument.Pages(sitePage).Shapes
    If oItem.Name <> "Sheet.2" Then
        'vsoDocument.Pages(sitePage).Select oItem.Item, visSelect ' NOW REMOVED
        oItem.DeleteEx (visDeleteNormal)
        Debug.Print oItem.Name
    End If
Next oItem

更新:根据您的回复和完整性检查,您是对的,我不需要 select 形状。我已经修改了代码以现在只显示 oItem.DeleteEx (visDeleteNormal) 并且这按预期工作。但是,我的 sheet 上留下了一些形状,例如名称为 "Ethernet.46" 的形状。我不知道为什么删除了一些形状,也不知道为什么删除了页面背景。我发现如果我 运行 我的 For 循环一次,将背景添加回 WITH vsoDocument.Pages(sitePage).BackPage,然后 运行 我的 For 循环再连续 5 次它最终删除所有形状。

问题:为什么我的 For 循环表现不可靠?

the .Select line fails, and I'm pretty sure it's the oItem.Item call that's failing as

Select 行失败,因为 Page 对象没有 Select 方法。这与 Window 对象有关。从 dox 看来,oItem.Item 也会失败,因此您可以只使用本身是 Shape 对象的 oItem

What is the correct syntax for this command in this loop?

可能如下:

vsoDocument.Application.ActiveWindow.Select oItem, visSelect 

但是,从您提供的代码中并不清楚:为什么需要 Select 形状? 通常这不是必需的。完全不依赖 Select 就可以完成您想做的事情。

Is there a way I could have fished for this information myself? e.g. can I reveal methods associated with the oItem definition, like "Name"?

您可以使用 VBE 中的“局部”窗格查看与每个对象关联的属性,并且可以从文档(通常包括语法示例和使用)或 VBE 中查看属性和方法按 F2 调出对象浏览器。

您可以在此处浏览 Visio 对象模型:

http://msdn.microsoft.com/en-us/library/office/ff765377.aspx

浏览该层次结构,您可以浏览 Shape 对象的事件、属性和方法:

https://msdn.microsoft.com/en-us/library/office/ff768546.aspx

更新

从集合中删除元素时,始终必须按索引并以相反的顺序执行此操作。

Dim i as Long
For i = vsoDocument.Pages(sitePage).Shapes.Count to 1 Step - 1
    Set oItem = vsoDocument.Pages(sitePage).Shapes(i)
    If oItem.Name <> "Sheet.2" Then
        Debug.Print oItem.Name
        oItem.DeleteEx (visDeleteNormal)
    End If
Next oItem

这是必要的原因是,当你 Delete 一个项目时,集合会重新索引自己,所以当你删除项目 #1 时,项目 #2 成为第一个索引,但是你的循环将您带到 下一个 项,现在是第 3 项。按索引强制循环,并以相反的顺序进行循环,可以防止这种不良行为。