In a previous example, I showed how to control variables in a Solid Edge sketch using a direct link to an Excel spreadsheet. In this example, I am going to show how to use VBA (Visual Basic for Applications) in Excel to control the variables in a Solid Edge sketch directly via the API.
1. Setup Excel VBA
Create a new file in Microsoft Excel.
Press Alt+F11 to enter the Microsoft Visual Basic window as shown below.
Right-click in the Project Explorer on the new file name (in this example, Book2) > Insert > Module.
2. Add References
To make Solid Edge type libraries available to the Visual Basic Object Browser, click References on the Tools menu (or Project menu depending on your version). On the References dialog box, select the Solid Edge libraries you want to access (specifically the Solid Edge Framework Type Library and Solid Edge Part Type Library).
All variable automation is accessed through the Variables collection and Variable objects. The Variables collection serves two purposes: it allows you to create and access variable objects, and it allows you to work with dimensions as variables.
3. The VBA Code
Write the following code into the VBA code area as shown below:
You can copy & paste the following code to your Excel VBA module:
' ================================================================= ' Example of using VBA code to control variables in Solid Edge document ' By AkeBlogger ' http://mechanical-design-handbook.blogspot.com/ ' ================================================================= Sub Simulate() On Error Resume Next 'Declare the program variables. Dim iAngle As Single Dim objApp As Object Dim objVariables As Object Dim objVariable As Object '------------------------------------------------------------------ ' Checking for the active document Set objApp = GetObject(, "SolidEdge.Application") If Err Then MsgBox "You must open Solid Edge before executing this module!!", vbOKOnly + vbExclamation, "Error" Exit Sub Else 'Connect to a running instance of Solid Edge. Set objApp = GetObject(, "SolidEdge.Application") 'Access the Variables collection. Set objVariables = objApp.ActiveDocument.Variables End If 'SIMULATION STARTS! For iAngle = 0 To 360 Step 2 ' Changing Cam_angle from 0, 2, 4, ..., 360 deg. Call objVariables.Edit("Cam_angle", iAngle) DoEvents ' Allow the system to update the screen Next iAngle End Sub
4. Prepare Solid Edge
Open the Solid Edge file from the previous example and delete the formula in the Variables Table as shown below. In this example, we will control the variable (dimension) using VBA code directly, so the link to the external spreadsheet must be removed.
5. Run Simulation
We are now ready for simulation. Resize the VBA Windows as shown below so you can see both applications, then click run to see the result.
Watch the following video for the actual result!
Comments