Sparx EA 12.0:如何通过VBScript调用内置功能自动布局图?
Automating Sparx EA 12 Diagram Layout with VBScript
Absolutely! You don’t need to waste time calculating element positions manually—Sparx EA 12’s API lets you directly trigger the same built-in layout logic that powers the "Layout Diagram" button in the Diagram Toolbox. Here are two reliable methods to automate this:
Method 1: Use the Diagram.AutoLayout Method
This method lets you specify exactly which layout algorithm to use (matching the options in the toolbox) and works without needing to activate the diagram in the EA UI.
Example VBScript Code:
' Initialize EA Repository connection Dim repo Set repo = CreateObject("EA.Repository") repo.OpenFile("C:\Path\To\Your\Model.eap") ' Replace with your model path ' Get the target diagram (replace 123 with your diagram's ID) Dim targetDiagram Set targetDiagram = repo.GetDiagramByID(123) ' Trigger auto-layout with your preferred algorithm ' Layout type constants (match toolbox options): ' 0 = Default, 1 = Hierarchical, 2 = Orthogonal, 3 = Symmetric, 4 = Circular, 5 = Force Directed targetDiagram.AutoLayout(1) ' Using Hierarchical layout here ' Save changes to the diagram and model targetDiagram.Update repo.Save ' Clean up repo.CloseFile Set targetDiagram = Nothing Set repo = Nothing
Method 2: Simulate the "Layout Diagram" Button Click with Repository.RunCommand
If you want to replicate the exact behavior of clicking the button (using the diagram’s current default layout settings), use this method. It activates the diagram in EA’s UI and runs the built-in command.
Example VBScript Code:
Dim repo Set repo = CreateObject("EA.Repository") repo.OpenFile("C:\Path\To\Your\Model.eap") ' Get and activate the target diagram Dim targetDiagram Set targetDiagram = repo.GetDiagramByID(123) repo.OpenDiagram(targetDiagram.DiagramID) ' Focus EA on this diagram ' Run the "Layout Diagram" command (command ID 2022 for EA 12) repo.RunCommand 2022, "" ' Save changes targetDiagram.Update repo.Save repo.CloseFile Set targetDiagram = Nothing Set repo = Nothing
Key Notes for Batch Processing:
- To process multiple diagrams, loop through the
Diagramscollection of a package:Dim pkg Set pkg = repo.GetPackageByID(456) ' Replace with your package ID For Each diag In pkg.Diagrams diag.AutoLayout(1) ' Or use RunCommand method diag.Update Next repo.Save - Always add error handling (e.g.,
On Error Resume Nextwith checks) to handle cases where diagrams might be locked or inaccessible. - Verify the command ID for
RunCommandmatches EA 12—2022 is correct for "Layout Diagram", but you can cross-reference EA’s official command ID docs if needed.
内容的提问来源于stack exchange,提问作者Grigorio
相关产品推荐
相关产品推荐

