[go: up one dir, main page]

0% found this document useful (0 votes)
50 views18 pages

SolidWorks PDF

The SOLIDWORKS API tutorials provide guidance on using the API with C#, VB.NET, and VBA to create macros for automating tasks like cut-extrudes. The tutorials cover recording, modifying, and debugging macros, as well as creating user forms for inputting parameters. Each tutorial requires approximately 45 minutes to complete and assumes familiarity with SOLIDWORKS software.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
50 views18 pages

SolidWorks PDF

The SOLIDWORKS API tutorials provide guidance on using the API with C#, VB.NET, and VBA to create macros for automating tasks like cut-extrudes. The tutorials cover recording, modifying, and debugging macros, as well as creating user forms for inputting parameters. Each tutorial requires approximately 45 minutes to complete and assumes familiarity with SOLIDWORKS software.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

SOLIDWORKS API Tutorials Page 1 of 18

SOLIDWORKS API Tutorials


The SOLIDWORKS Application Programming Interface (API) is the basis for the SOLIDWORKS three macro
recorders: C#, VB.NET, and VBA. Each of the three SOLIDWORKS API tutorials shows you how to:
Record a macro to create a cut-extrude on a specific pre-selected face on a part;
Modify the macro to create the cut-extrude on any pre-selected face on the part;
Create a form where users can specify the cut-extrude's radius and depth values and create the cut-
extrude on any pre-selected face on the part.
These are done using the SOLIDWORKS C#, VB.NET, or VBA macro recorder. Click a link to open the
SOLIDWORKS API tutorial using that macro recorder.

C# VB.NET VBA

Time: 45 minutes Record and Time: 45 minutes Record and Time: 45 minutes Record and
modify a C# macro. modify a VB.NET macro. modify a VBA macro.

SOLIDWORKS API C# Overview


This tutorial introduces you to the SOLIDWORKS® Application Programming Interface (API) and the
SOLIDWORKS Visual Studio® Tools for Applications integrated development environment (VSTA 1.0).
Before using this tutorial, you must enable VSTA 1.0 in SOLIDWORKS. To enable VSTA 1.0, deselect
Tools > Options > System Options > Enable VSTA VERSION 3.0 in the SOLIDWORKS menu.
The SOLIDWORKS API:
is the basis for the SOLIDWORKS macro recorders.
lets you automate and customize the SOLIDWORKS software and integrate your software with the
SOLIDWORKS software.
The quickest and easiest way to start programming with the SOLIDWORKS API is to record a macro. Then
you can modify the macro to fit your work site's needs. This tutorial provides instructions on recording,
editing, and running a macro written in C# in the SOLIDWORKS software using VSTA 1.0.
This tutorial assumes that you are familiar with using the SOLIDWORKS software interactively. If you plan
on automating, customizing, or integrating your software with the SOLIDWORKS software using the
SOLIDWORKS API, you should take a Visual Basic or Visual C# programming course and then attend a
SOLIDWORKS API training course offered at a SOLIDWORKS Authorized Training and Support Center.

Recording a Macro
Create a SOLIDWORKS API C# program by recording the operations performed to create a cut-extrude on
a face. The SOLIDWORKS macro recorder records every operation you perform while recording.

1. Click here to open the candlestick part (or browse to drive letter:\Users\Public\Public
Documents\SOLIDWORKS\SOLIDWORKS version\samples\tutorial\api\cstick.sldprt.)

2. Click Options (Standard toolbar), make sure Automatically edit macro after recording is
not selected and Stop VSTA debugger on macro exit is selected.

3. Click OK.

4. Click Record\Pause Macro (Macro toolbar) to begin recording the macro.

5. Select the face shown.

6. Click Sketch (Sketch toolbar) to insert a sketch.

file:///C:/Users/ABDELHAMID/AppData/Local/Temp/~hh4993.htm 13-Aug-24
SOLIDWORKS API Tutorials Page 2 of 18

7. Click Normal To (Standard Views toolbar).

Sketching a Circle

1. Click Circle (Sketch toolbar).

2. Sketch a circle centered at the sketch origin.

3. In the PropertyManager, set Radius to 15.

4. Click .

Saving a Macro

1. Click Extruded Cut (Features toolbar).

2. In the PropertyManager, under Direction 1:


Set End Condition to Blind.

Set Depth to 25.

Click Draft On/Off , and set Draft Angle to 15.

3. Click .
A cut-extrude with a radius of 15mm, depth of 25mm, and draft of 15° centered on the top face of
the candlestick holder is created.

4. Click Stop Macro (Macro toolbar) to stop recording the macro.

5. In the Save As dialog box, browse to the folder where you want to save the macro.

6. Make sure Save as type is SW VSTA C# Macro (*.csproj).

7. Type CreateCutExtrudeCSharp in File name.

8. Click Save.

Examining a Macro

1. Click Edit Macro (Macro toolbar).

2. Open CreateCutExtrudeCSharp.csproj.

Make sure that the file type is set as SW VSTA C# Macro (*.csproj).

3. Click Open.
The SOLIDWORKS VSTA IDE opens. The Code Editor window contains the SOLIDWORKS API C# code
generated for the macro.

Modifying a Macro
Certain variables are declared automatically in a SOLIDWORKS macro. You can delete any variables not
used in the program.

1. Delete these variables declarations.


PartDoc swPart = null;
DrawingDoc swDrawing = null;
AssemblyDoc swAssembly = null;

int longstatus = 0;
int longwarnings = 0;

2. Test the modified macro by recreating the cut-extrude in the candlestick holder.
a. In the SOLIDWORKS software, drag the rollback bar up the FeatureManager design tree until it
is above the Cut-Extrude1 feature.

b. In the SOLIDWORKS VSTA IDE, click Start Debugging .


A new cut-extrude is created in the candlestick holder.

file:///C:/Users/ABDELHAMID/AppData/Local/Temp/~hh4993.htm 13-Aug-24
SOLIDWORKS API Tutorials Page 3 of 18

3. Delete the cut-extrude and the sketch just created.

4. Drag the rollback bar back to the bottom of the FeatureManager design tree.

5. Delete the original cut-extrude and sketch.

Starting to Debug a Program


To learn how to debug code in C#, change the code in the Code Editor window to cause errors to occur
while executing it.

1. Delete the letters el from the variable ModelDoc2 and change the name of the property ActiveDoc
to ActiveDoc2.

You must stop a running macro before you can edit it.

2. In the SOLIDWORKS graphics area, select the top face.

Finishing Debugging a Program

1. Click Start Debugging in the SOLIDWORKS VSTA IDE.


A message box is displayed informing you that there were build errors.

2. To debug the errors, click No.

3. Double-click the first error to move the cursor to the line of code that contains the error.

4. Insert the letters el so ModDoc2 becomes ModelDoc2, which is a declared variable in the code.

5. Click Start Debugging .

6. Click No and change ActiveDoc2 to ActiveDoc.

7. Click Start Debugging .


The code compiles, and a cut-extrude is created on the selected face.

8. Delete the cut-extrude and sketch.

Creating a Generic Cut-Extrude Program


Modify the macro in the Code Editor window so that you can create a cut-extrude on any pre-selected face
in any part. To make the program more generic, eliminate the draft.

1. Click here for instructions on how to modify your macro.

2. Click Save SolidWorksMacro.cs in the SOLIDWORKS VSTA IDE to save the modified code.

3. In the SOLIDWORKS graphics area, select the face on the bottom of the part.

4. Click Start Debugging in the SOLIDWORKS VSTA IDE.


A cut-extrude with a radius of 15mm and a depth of 25mm is created on the selected face and is
centered on the sketch point.

5. Delete the cut-extrude and sketch.

Creating a Form
Currently you must modify the code to change the radius and depth values programmatically. To increase
the flexibility of the program, you can create a C# form where users can specify these values.

file:///C:/Users/ABDELHAMID/AppData/Local/Temp/~hh4993.htm 13-Aug-24
SOLIDWORKS API Tutorials Page 4 of 18

1. In the SOLIDWORKS VSTA IDE, click View > Project Explorer .

2. In the Project Explorer, select SolidWorksMacro.cs.

3. Click Project > Add Windows Form.

4. Select Windows Form, leave Form1.cs in Name, and click Add.

5. To change the name of the form, click the form in the Design View window.

6. Click View > Properties Window to display the properties associated with Form1.

7. Type frmCutExtrude in the (Name) row in the Properties window.

Use the scroll bar in the Properties window to locate the (Name) row, which is near the
beginning of the Properties window.

8. Click the form for the change to take effect.


The name at the top of the Properties window changes to frmCutExtrude. However, the name
shown on the form is the Text property of the form, which you did not change, so it remains Form1.

Adding Controls
Add two text boxes and a command button, called controls, to the form using the Toolbox.

1. Display the toolbox by clicking View > Toolbox.

2. Expand Common Controls.

3. Drag and place it near the upper-right corner of the form.

4. Drag another text box and place it below the text box that you just created.

5. Drag , place it below the text boxes, and stretch it so that it is the same length as the
text boxes.

Changing Names of Controls


Change the names of the text boxes and the command button to more meaningful names.

1. Click the top text box on the form.

2. Type txtRadius in the (Name) row in the Properties window.

3. Click outside the row for the change to take effect.

4. Click the other text box and name it txtDepth.

5. Click the command button and name it bOK.

Finishing the Form


Add labels for both text boxes so that users know what information to type in the text boxes. Also, change
the caption on the command button.

1. Drag and place it beside the top text box.

2. Type Radius: in the Text row in the Properties window.

3. Click anywhere on the form.

file:///C:/Users/ABDELHAMID/AppData/Local/Temp/~hh4993.htm 13-Aug-24
SOLIDWORKS API Tutorials Page 5 of 18

4. Place a label named Depth: beside the other text box.

5. Click button1 on the form and change its text to OK.

6. Click anywhere on the form.

Writing Code for the Form


C# can insert code templates for event procedures for controls. You modify the code template to specify
what you want to happen when an event occurs, such as when users click the OK button.

1. Double-click the OK button on the form to open the Code Editor window containing an event
procedure for this control.
The name of the event procedure, bOK_Click, is a combination of the control's name as specified in
the control's Name property, an underscore (_), and the name of the event. The Click procedure is
the default procedure for a command button.

2. Type, or copy and paste, these declarations above Private void bOK_Click(object sender,
EventArgs e).

public double radius;


public double depth;

3. Type, or copy and paste, this code between Private void bOK_Click(object sender, EventArgs
e)event's curly brackets.
double radiusResult;
double depthResult;

//Convert strings to doubles and
//make sure that the text in the two
//text boxes on the form are positive,
//non-zero, numeric values
double.TryParse(txtRadius.Text, out radiusResult);
double.TryParse(txtDepth.Text, out depthResult);
if (radiusResult > 0 && depthResult > 0)
{
radius = radiusResult;
depth = depthResult;
//Close the form and continue
Close();
}
else
{
//Display a message box telling the user to type
//positive, non-zero, numeric values in both text boxes

MessageBox.Show("You must type positive, non-zero, numeric values in both Radius and Depth.");
}
 
Adding Variables for Controls

file:///C:/Users/ABDELHAMID/AppData/Local/Temp/~hh4993.htm 13-Aug-24
SOLIDWORKS API Tutorials Page 6 of 18

Modify SolidWorksMacro.cs to display the form to users and to retrieve the depth and radius values
from the form.

1. Double-click SolidWorksMacro.cs in the Project Explorer to display its code in the Code Editor
window.

2. Scroll to the top of the macro and locate swDoc = ((ModelDoc2)(swApp.ActiveDoc));.

3. Insert the following code between swDoc = ((ModelDoc2)(swApp.ActiveDoc)); and //COMMENT OUT
THIS LINE OF CODE to display the form and retrieve the depth and radius values typed by the user.
//ADD THESE LINES OF CODE
double holeRadius;
double holeDepth;
//Create an instance of the user form
frmCutExtrude myForm = new frmCutExtrude();

//Set the title for the form


myForm.Text = "Size of Cut-Extrude in Millimeters";
//Display the user form and retrieve radius and
//depth values typed by the user; divide those values
//by 1000 to change millimeters to meters
myForm.ShowDialog();
holeRadius = myForm.radius / 1000;
holeDepth = myForm.depth / 1000;
//Dispose of the user form and remove it from
//memory because it's no longer needed
myForm.Dispose();

Saving the Code for the Form


Replace the radius and depth values, which were automatically inserted by the SOLIDWORKS macro
recorder when you created the cut-extrude in the SOLIDWORKS user interface, with variables.

1. Scroll to near the bottom of the macro and locate dz = darray[2];.

2. Replace all of the code appearing after dz = darray[2]; with this code.
//Create the sketch for cut-extrude
SketchSegment swSketchSegment = null;

swSketchSegment = (SketchSegment)swDoc.SketchManager.CreateCircleByRadius(dx, dy, dz, holeRadius);
//Create the cut-extrude feature
Feature swFeature = null;
swFeature = (Feature)swDoc.FeatureManager.FeatureCut3(true, false, false, 0, 0, holeDepth, 0.01, true, false, false, false

}
}
//KEEP THESE LINES OF CODE
///<summary>
///The Sldworks swApp variable is pre-assigned for you.
///</summary>
public SldWorks swApp;

}
 
3. Click Project > CreateCutExtrudeCSharp Properties > Build, and make sure that bin\Debug
appears in Output path.

4. Click Save SolidWorksMacro.cs to save the modified code.

Testing the Program and Form


Now test the modified program and the form.

1. In the SOLIDWORKS software, select the bottom face of the candlestick holder.

2. Click Start Debugging in the SOLIDWORKS VSTA IDE.


The Size of Cut-Extrude in Millimeters dialog is displayed.

3. Type 15 in Radius and 10 in Depth.

4. Click OK to create a cut-extrude of the specified depth and radius on the bottom face.

5. Click File > Exit in the SOLIDWORKS VSTA IDE to exit it and return to SOLIDWORKS.

Congratulations! You have completed this tutorial.


Return to the tutorials overview page.

SOLIDWORKS API VB.NET Overview

file:///C:/Users/ABDELHAMID/AppData/Local/Temp/~hh4993.htm 13-Aug-24
SOLIDWORKS API Tutorials Page 7 of 18

This tutorial introduces you to the SOLIDWORKS® Application Programming Interface (API) and the
SOLIDWORKS Visual Studio® Tools for Applications integrated development environment (VSTA 1.0).
Before using this tutorial, you must enable VSTA 1.0 in SOLIDWORKS. To enable VSTA 1.0, deselect
Tools > Options > System Options > Enable VSTA VERSION 3.0 in the SOLIDWORKS menu.
The SOLIDWORKS API:
Is the basis for the SOLIDWORKS macro recorders.
Lets you automate and customize the SOLIDWORKS software and integrate your software with the
SOLIDWORKS software.
The quickest and easiest way to start programming with the SOLIDWORKS API is to record a macro. Then
you can modify the macro to fit your work site's needs. This tutorial provides instructions on recording,
editing, and running a macro written in Visual Basic (VB.NET) in the SOLIDWORKS software using VSTA
1.0.
This tutorial assumes that you are familiar with using the SOLIDWORKS software interactively. If you plan
on automating, customizing, or integrating your software with the SOLIDWORKS software using the
SOLIDWORKS API, you should take a Visual Basic or Visual C# programming course and then attend a
SOLIDWORKS API training course offered at a SOLIDWORKS Authorized Training and Support Center.

Recording a Macro
Create a SOLIDWORKS API VB.NET program by recording the operations performed to create a cut-
extrude on a face. The SOLIDWORKS macro recorder records every operation you perform while
recording.

1. Click here to open the candlestick part (or browse to drive letter:\Users\Public\Public
Documents\SOLIDWORKS\SOLIDWORKS version\samples\tutorial\api\cstick.sldprt.)

2. Click Options (Standard toolbar) and make sure Automatically edit macro after recording
is not selected and Stop VSTA debugger on macro exit is selected.

3. Click OK.

4. Click Record\Pause Macro (Macro toolbar) to begin recording the macro.

5. Select the face shown.

6. Click Sketch (Sketch toolbar) to insert a sketch.

7. Click Normal To (Standard Views toolbar).

Sketching a Circle

1. Click Circle (Sketch toolbar).

2. Sketch a circle centered at the sketch origin.

3. In the PropertyManager, set Radius to 15.

4. Click .

Saving a Macro

1. Click Extruded Cut (Features toolbar).

2. In the PropertyManager, under Direction 1:


Set End Condition to Blind.

Set Depth to 25.

Click Draft On/Off , and set Draft Angle to 15.

file:///C:/Users/ABDELHAMID/AppData/Local/Temp/~hh4993.htm 13-Aug-24
SOLIDWORKS API Tutorials Page 8 of 18

3. Click .
A cut-extrude with a radius of 15mm, depth of 25mm, and draft of 15° centered on the top face of
the candlestick holder is created.

4. Click Stop Macro (Macro toolbar) to stop recording the macro.

5. In the Save As dialog box, browse to the folder where you want to save the macro.

6. Make sure Save as type is SW VSTA VB Macro (*.vbproj).

7. Type CreateCutExtrudeVBNET in File name.

8. Click Save.

Examining a Macro

1. Click Edit Macro (Macro toolbar).

2. Open CreateCutExtrudeVBNET.vbproj.

Make sure that the file type is set as SW VSTA VB Macro (*.vbproj).

The SOLIDWORKS VSTA IDE opens. The Code Editor window contains the SOLIDWORKS API VB.NET
code generated for the macro.

Modifying a Macro
Creating associations between two entities is called binding. For example, in the VB.NET line of code Dim
boolstatus as Boolean = false, the variable named boolstatus is associated, or bound, to the data
type Boolean. When binding occurs at compile time, it is called early binding. To avoid problems like
misnamed variables and to reduce debugging time and improve the performance of your program, you
should explicitly declare and bind variables early.

1. Type Option Explicit On at the top of the program, above Imports


SolidWorks.Interop.sldworks to ensure that all variables are explicity declared.
Certain variables are declared automatically in a SOLIDWORKS macro. You can delete any variables
not used in the program.

2. Delete these variables declarations.


Dim swPart As PartDoc = Nothing
Dim swDrawing As DrawingDoc = Nothing
Dim swAssembly As AssemblyDoc = Nothing

Dim longstatus As Integer = 0


Dim longwarnings As Integer = 0

3. Test the modified macro by recreating the cut-extrude in the candlestick holder.
a. In the SOLIDWORKS software, drag the rollback bar up the FeatureManager design tree until it
is above the Cut-Extrude1 feature.

b. In the Solidworks Visual Studio for Applications IDE, click Start Debugging .
A new cut-extrude is created in the candlestick holder.

4. Delete the cut-extrude and the sketch just created.

5. Drag the rollback bar back to the bottom of the FeatureManager design tree.

6. Delete the original cut-extrude and sketch.

Starting to Debug a Program


To learn how to debug code in VB.NET, change the code in the Code Editor window to cause errors to
occur while executing it.

1. Delete the letters el from the variable ModelDoc2 and change the name of the property ActiveDoc
to ActiveDoc2.

file:///C:/Users/ABDELHAMID/AppData/Local/Temp/~hh4993.htm 13-Aug-24
SOLIDWORKS API Tutorials Page 9 of 18

You must stop a running macro before you can edit it.

2. In the SOLIDWORKS graphics area, select the top face.

3. Click Start Debugging in the SOLIDWORKS VSTA IDE.


A message box is displayed informing you that there was a build error.

4. To debug the error, click No.


The error is displayed in the Error List window in the SOLIDWORKS VSTA IDE.

Finishing Debugging a Program

1. Double-click the error to move the cursor to the line of code that contains the error.

2. Insert the letters el so ModDoc2 becomes ModelDoc2, which is a declared variable in the code.

3. Click Start Debugging to finish executing the program and to create a cut-extrude on the
selected face.

4. Close the message box and click Stop Debugging.

5. Change ActiveDoc2 back to ActiveDoc and press the Tab key to accept ActiveDoc, which is
highlighted in IntelliSense.
As you type or modify code in the Code Editor window, a list containing similarly spelled objects,
methods, and properties is displayed. This list is IntelliSense, Microsoft's autocompletion system.
When the correct object, method, or property is selected in the list, press the Tab key to insert it in
your program.

6. Click Start Debugging to compile the code and to create a cut-extrude on the selected face.

7. Delete the cut-extrude and sketch.

Creating a Generic Cut-Extrude Program


Modify the macro in the Code Editor window so that you can create a cut-extrude on any pre-selected face
in any part. To make the program more generic, eliminate the draft.

1. Click here for instructions on how to modify your macro.

2. Click Save SolidWorksMacro.vb in the SOLIDWORKS VSTA IDE to save the modified code.

3. In the SOLIDWORKS graphics area, select the face on the bottom of the part.

4. Click Start Debugging in the SOLIDWORKS VSTA IDE.


A cut-extrude with a radius of 15mm and a depth of 25mm is created on the selected face and is
centered on the sketch point.

5. Delete the cut-extrude and sketch.

Creating a Form
Currently you must modify the code to change the radius and depth values programmatically. To increase
the flexibility of the program, you can create a VB.NET form where users can specify these values.

1. In the SOLIDWORKS VSTA IDE, click View > Project Explorer.

file:///C:/Users/ABDELHAMID/AppData/Local/Temp/~hh4993.htm 13-Aug-24
SOLIDWORKS API Tutorials Page 10 of 18

2. In the Project Explorer, select SolidWorksMacro.vb.

3. Click Project > Add Windows Form.

4. Select Windows Form, leave Form1.vb in Name, and click Add.

5. To change the name of the form, click the form in the Design View window.

6. Click View > Properties Window to display the properties associated with Form1.

7. Type frmCutExtrude in the (Name) row in the Properties window.

Use the scroll bar in the Properties window to locate the (Name) row, which is near the
beginning of the Properties window.

8. Click the form for the change to take effect.


The name shown on the form is the Text property of the form, which you did not change, so it
remains Form1.

Adding Controls
Add two text boxes and a command button, called controls, to the form using the Toolbox.

1. Display the toolbox by clicking View > Toolbox.

2. Expand Common Controls.

3. Drag and place it near the upper-right corner of the form.

4. Drag another text box and place it below the text box that you just created.

5. Drag , place it below the text boxes, and stretch it so that it is the same length as the
text boxes.

Changing Names of Controls


Change the names of the text boxes and the command button to more meaningful names.

1. Click the top text box on the form.

2. Type txtRadius in the (Name) row in the Properties window.

3. Click outside the row for the change to take effect.

4. Click the other text box and name it txtDepth.

5. Click the command button and name it bOK.

Finishing the Form


Add labels for both text boxes so that users know what information to type in the text boxes. Also, change
the caption on the command button.

file:///C:/Users/ABDELHAMID/AppData/Local/Temp/~hh4993.htm 13-Aug-24
SOLIDWORKS API Tutorials Page 11 of 18

1. Drag and place it beside the top text box.

2. Type Radius: in the Text row in the Properties window.

3. Click anywhere on the form.

4. Place a label named Depth: beside the other text box.

5. Click Button1 on the form and change its text to OK.

6. Click anywhere on the form.

Writing Code for the Form


VB.NET can insert code templates for event procedures for controls. You modify the code template to
specify what you want to happen when an event occurs, such as when users click the OK button.

1. Double-click the OK button on the form to open the Code Editor window containing an event
procedure for this control.
The name of the event procedure, bOK_Click, is a combination of the control's name as specified in
the control's Name property, an underscore (_), and the name of the event. The Click procedure is
the default procedure for a command button.

2. Type, or copy and paste, these declarations above Private Sub bOK_Click(ByVal sender As
System.Object, ByVal e As System.EventArgs) Handles bOK.Click).
Public depth As Double = 0
Public radius As Double = 0

3. Type, or copy and paste, this code between Private Sub bOK_Click(ByVal sender As
System.Object, ByVal e As System.EventArgs) Handles bOK.Click) and End Sub.
' Convert strings to doubles and
' make sure that the text in the two text boxes on
' the form are positive, non-zero, numeric values

Dim radiusResult As Double = 0
Dim depthResult As Double = 0
Double.TryParse(txtRadius.Text, radiusResult)
Double.TryParse(txtDepth.Text, depthResult)
If (radiusResult > 0 and depthResult > 0) Then
radius = radiusResult
depth = depthResult
' Close the form and continue
Close()
Else
' Display a message box telling the user to type
' positive, non-zero, numeric values in both text
' boxes

MsgBox("You must type positive, non-zero, numeric values for both Radius and Depth.")
 
Adding Variables for Controls

file:///C:/Users/ABDELHAMID/AppData/Local/Temp/~hh4993.htm 13-Aug-24
SOLIDWORKS API Tutorials Page 12 of 18

Modify SolidWorksMacro.vb to display the form to users and to retrieve the depth and radius values
from the form.

1. Double-click SolidWorksMacro.vb in the Project Explorer to display its code in the Code Editor
window.

2. Scroll to the top of the macro and locate swDoc = CType(swApp.ActiveDoc, ModelDoc2).

3. Insert the following code between swDoc = CType(swApp.ActiveDoc, ModelDoc2) and 'COMMENT
OUT THESE LINES OF CODE to display the form and retrieve the depth and radius values typed by
the user.
Dim HoleRadius As Double = 0
Dim HoleDepth As Double = 0

' Create an instance of the user form


Dim myForm as New frmCutExtrude

' Set the caption for the form


myForm.Text = "Size of Cut-Extrude in Millimeters"

' Display the user form and retrieve radius


' and depth values entered by users
' Divide the values by 1000 to change
' millimeters to meters
myForm.ShowDialog()
HoleRadius = myForm.radius / 1000
HoleDepth = myForm.depth / 1000

' Destroy the user form and remove it from memory


' because it is no longer needed
Set myForm = Nothing

Saving the Code for the Form


Replace the radius and depth values, which were automatically inserted by the SOLIDWORKS macro
recorder when you created the cut-extrude in the SOLIDWORKS user interface, with variables.

1. Scroll to near the bottom of the macro and locate dz = swMathPoint.ArrayData(2).

2. Replace all of the code appearing after dz = swMathPoint.ArrayData(2) with this code.
'Sketch circle centered on the sketch point
swSketchManager.CreateCircleByRadius(dx, dy, dz, HoleRadius)

'Create cut-extrude without draft


Dim swFeatureManager As FeatureManager = Nothing
swFeaturemanager = swDoc.FeatureManager
swFeatureManager.FeatureCut3(True, False, False, _
0, 0, HoleDepth, 0.01, True, False, False, False, _
0, 0, False, False, False, False, False, True, True, _
False, False, False, swStartConditions_e.swStartSketchPlane, 0, False)
End If

End Sub

'''<summary>
''' The Sldworks swApp variable is pre-assigned for you.
''' </summary>
Public swApp as SldWorks
End Class

3. Click Save SolidWorksMacro.vb to save the modified code.

Testing the Program and Form


Now test the modified program and the form.

1. In the SOLIDWORKS software, select the bottom face of the candlestick holder.

2. Click Start Debugging in the SOLIDWORKS VSTA IDE.


The Size of Cut-Extrude in Millimeters dialog is displayed.

3. Type 15 in Radius and 10 in Depth.

4. Click OK to create a cut-extrude of the specified depth and radius on the bottom face.

5. Click File > Exit in the SOLIDWORKS VSTA IDE to exit it and return to SOLIDWORKS.

6. Select the bottom face of the candlestick holder again.

file:///C:/Users/ABDELHAMID/AppData/Local/Temp/~hh4993.htm 13-Aug-24
SOLIDWORKS API Tutorials Page 13 of 18

Congratulations! You have completed this tutorial.


Return to the tutorials overview page.

SOLIDWORKS API VBA Overview


This tutorial introduces you to the SOLIDWORKS® Application Programming Interface (API), the
SOLIDWORKS VBA macro recorder, and the Microsoft® Visual Basic® for Applications (VBA) Integrated
Development Environment (IDE).
The SOLIDWORKS API:
Is the basis for the SOLIDWORKS macro recorders.
Lets you automate and customize the SOLIDWORKS software and integrate your software with the
SOLIDWORKS software.
The quickest and easiest way to start programming with the SOLIDWORKS API is to record a macro. Then
you can modify the macro to fit your work site's needs. This tutorial provides instructions on recording,
editing, and running a macro written in VBA in the SOLIDWORKS software.
This tutorial assumes that you are familiar with using the SOLIDWORKS software interactively. If you plan
on automating, customizing, or integrating your software with the SOLIDWORKS software using the
SOLIDWORKS API, you should take a Visual Basic or Visual C# programming course and then attend a
SOLIDWORKS API training course offered at a SOLIDWORKS Authorized Training and Support Center.

Recording a Macro
Create a SOLIDWORKS API VBA program by recording the operations performed to create a cut-extrude
on a face. The SOLIDWORKS macro recorder records every operation you perform while recording.

1. Click here to open the candlestick part (or browse to drive letter:\Users\Public\Public
Documents\SOLIDWORKS\SOLIDWORKS version\samples\tutorial\api\cstick.sldprt.)

2. Click Record\Pause Macro (Macro toolbar) to begin recording the macro.

3. Select the face shown.

4. Click Sketch (Sketch toolbar) to insert a sketch.

5. Click Normal To (Standard Views toolbar).

Sketching a Circle

1. Click Circle (Sketch toolbar).

2. Sketch a circle centered at the sketch origin.

3. In the PropertyManager, set Radius to 15.

4. Click .

Saving a Macro

1. Click Extruded Cut (Features toolbar).

2. In the PropertyManager, under Direction 1:


Set End Condition to Blind.

Set Depth to 25.

Click Draft On/Off , and set Draft Angle to 15.

3. Click .

file:///C:/Users/ABDELHAMID/AppData/Local/Temp/~hh4993.htm 13-Aug-24
SOLIDWORKS API Tutorials Page 14 of 18

A cut-extrude with a radius of 15mm, depth of 25mm, and draft of 15° centered on the top face of
the candlestick holder is created.

4. Click Stop Macro (Macro toolbar) to stop recording the macro.

5. In the Save As dialog box, browse to the folder where you want to save the macro.

6. Make sure Save as type is SW VBA Macros (*.swp).

7. Type CreateCutExtrudeVBA in File name.

8. Click Save.

Examining a Macro

1. Click Edit Macro (Macro toolbar).

2. Open CreateCutExtrudeVBA.swp.

Make sure that the file type is set as SW VBA Macros (*.swp).

3. Click Open.
The Visual Basic Editor and the Code window open. The Code window contains the SOLIDWORKS API
code generated for the macro.

4. If Part.SketchManager.InsertSketch True does not appear in your code, type


Part.SketchManager.InsertSketch True before Part.ClearSelection2 True.

5. Close the browser displaying the code. Leave the Code window open.

Modifying a Macro
To avoid problems like misnamed variables and to improve the performance of your program, you should
explicitly declare and bind variables early.

1. To explicitly declare all variables, type Option Explicit at the top of the program, before Dim
swApp As Object.

Option Explicit
Dim swApp As Object
About Binding
Certain variables are declared automatically in a SOLIDWORKS macro. You can delete any variables
not used in the program.

2. Delete these variables declarations.


Dim longstatus As Long, longwarnings As Long

3. Modify the swApp and Part variables to make them early bound.
Dim swApp As SldWorks.SldWorks
Dim Part As SldWorks.ModelDoc2

As you type code in the Code window, a list containing similarly spelled objects, methods, and
properties is displayed. When the correct object, method, or property is selected in the list,
press the Tab key to insert it in your program.

4. In the Solidworks software, drag the rollback bar up the FeatureManager design tree until it is above
the Cut-Extrude1 feature.

5. In the Visual Basic editor, click Run Sub/UserForm .

6. In the Macros dialog box, click Run.


A new cut-extrude is created in the candlestick holder.

7. Delete the cut-extrude and sketch just created.

8. Drag the rollback bar back to the bottom of the FeatureManager design tree.

9. Delete the original cut-extrude and sketch.

Starting to Debug a Program


To learn how to debug code in Visual Basic, change the code in the Code window to cause errors to occur
while executing it.

file:///C:/Users/ABDELHAMID/AppData/Local/Temp/~hh4993.htm 13-Aug-24
SOLIDWORKS API Tutorials Page 15 of 18

1. Delete the letter r from the variable Part and change the name of the method InsertSketch to
InsertSketch2.

You must stop a running macro before you can edit it.

2. In the SOLIDWORKS graphics area, select the top face.

Running a Macro

1. Click Run Macro (Macro toolbar).

2. Open CreateCutExtrudeVBA.swp.
A message box informs you that the code contains an undefined variable. Because the program
contains the Option Explicit statement, all variables in the program must be defined.

3. Click OK.
The offending code is selected in the Code window. The yellow arrow in the left margin indicates that
execution resumes at this line of code.

4. Click the selected code, and insert the letter r. Pat becomes Part, which is a declared variable in the
code.

Finishing Debugging a Program

1. Click Continue in the Visual Basic Editor.


A message box is displayed informing you that the code contains a runtime error. An object does not
support the specified method or property.

2. Click Debug.
The offending code is highlighted in yellow. This object does not have an InsertSketch2 method.

3. Change InsertSketch2 back to InsertSketch.

4. Click Continue to finish executing the program and to create a cut-extrude on the selected
face.

5. Delete the cut-extrude and sketch.

Creating a Generic Cut-Extrude Program


Modify the macro in the Code window so that you can create a cut-extrude on any pre-selected face in
any part. To make the program more generic, eliminate the draft.

1. Click here for instructions on how to modify your macro.

2. Click Save CreateCutExtrudeVBA in the Visual Basic Editor to save the modified code.

3. In the SOLIDWORKS graphics area, select the face on the bottom of the part.

4. Click Run Sub/UserForm in the Visual Basic Editor.


A cut-extrude with a radius of 15mm and a depth of 25mm is created on the selected face and is
centered on the sketch point.

5. Delete the cut-extrude and sketch.

Creating a Form
Currently you must modify the code to change the radius and depth values programmatically. To increase
the flexibility of the program, you can create a Visual Basic form where users can specify these values.

file:///C:/Users/ABDELHAMID/AppData/Local/Temp/~hh4993.htm 13-Aug-24
SOLIDWORKS API Tutorials Page 16 of 18

1. In the Visual Basic Editor, click View > Project Explorer .

2. In the Project Explorer, right-click the CreateCutExtrudeVBA1 module.

3. Click Insert > UserForm to add a blank form called UserForm1 to the project and to display the
Toolbox.

4. Click View > Properties Window to display the properties associated with UserForm1.

5. To change the name of the form, click UserForm1 in the Project Explorer.

If you do not see UserForm1 in the Project Explorer, drag the window downward to lengthen it.

6. Type frmCutExtrude in the (Name) row in the Properties window.

7. Click the form for the change to take effect.


The name at the top of the Properties window and the name of the form module in the Project
Explorer change to frmCutExtrude. However, the name shown on the form is the Caption property
of the form, which you did not change, so it remains UserForm1.

Adding Controls
Add two text boxes and a command button, called controls, to the form using the Toolbox.

1. Drag TextBox and place it near the upper-right corner of the form.

2. Drag another text box and place it below the text box that you just created.

3. Drag CommandButton and place it below the text boxes.

Changing Names of Controls


Change the names of the text boxes and the command button to more meaningful names.

1. Click the top text box on the form.

2. Type txtRadius in the (Name) row in the Properties window.

3. Click outside the row for the change to take effect.

4. Click the other text box and name it txtDepth.

5. Click the command button and name it bOK.

Finishing the Form


Add labels for both text boxes so that users know what information to type in the text boxes. Also, change
the caption on the command button.

1. Drag Label and place it beside the top text box.

2. Type Radius: in the Caption row in the Properties window.

3. Click anywhere on the form.

file:///C:/Users/ABDELHAMID/AppData/Local/Temp/~hh4993.htm 13-Aug-24
SOLIDWORKS API Tutorials Page 17 of 18

4. Place a label named Depth: beside the other text box.

5. Click CommandButton1 on the form and change its caption to OK.

6. Click anywhere on the form.

Writing Code for the Form


Visual Basic can insert code templates for event procedures for controls. You modify the code template to
specify what you want to happen when an event occurs, such as when users click the OK button.

1. Double-click the OK button on the form to open the Code window containing an event procedure for
this control.
The name of the event procedure, bOK_Click, is a combination of the control's name as specified in
the control's Name property, an underscore (_), and the name of the event. The Click procedure is
the default procedure for a command button.

2. Type, or copy and paste, these declarations above Private Sub bOK_Click().
Public depth As Double
Public radius As Double

3. Type, or copy and paste, this code between Private Sub bOK_Click() and End Sub.
' Make sure that the text in the two text boxes on the
' form, txtDepth and txtRadius, is numerical
If IsNumeric(txtDepth.text) And IsNumeric(txtRadius.text) Then
depth = txtDepth.text
radius = txtRadius.text
' Close the dialog box and continue
Hide
Else
' Display a message box telling users to enter numerical
' values for both depth and radius
MsgBox "You must type numeric values for both depth and radius."
End If

Adding Variables for Controls


Modify the CreateCutExtrudeVBA1 module to display the form to users and to retrieve the depth and
radius values from the form.

1. Double-click CreateCutExtrudeVBA1 in the Project Explorer to display its code in the Code window.

2. Add these two variables after Dim dz As Double.


Dim HoleRadius As Double
Dim HoleDepth As Double

3. Add this code after Set Part = swApp.ActiveDoc and before ' CODE TO COMMENT OUT to display
the form and retrieve the depth and radius values entered by users.

file:///C:/Users/ABDELHAMID/AppData/Local/Temp/~hh4993.htm 13-Aug-24
SOLIDWORKS API Tutorials Page 18 of 18

' Create an instance of the user form


Dim myForm as New frmCutExtrude

' Set the caption for the form


myForm.Caption = "Size of Cut-Extrude in Millimeters"

' Display the user form and retrieve radius and depth
' values entered by users
' Divide the values by 1000 to change millimeters to meters
myForm.Show
HoleRadius = myForm.radius / 1000
HoleDepth = myForm.depth / 1000

' Destroy the user form and remove it from memory


' because it is no longer needed
Set myForm = Nothing

Saving the Code for the Form


Replace the radius and depth values, which were automatically inserted by the SOLIDWORKS macro
recorder when you created the cut-extrude in the SOLIDWORKS user interface, with variables.

1. Replace all of the code appearing after dz = SketchPoint.ArrayData(2) with this code.
'Sketch circle centered on the sketch point
Part.SketchManager.CreateCircleByRadius dx, dy, dz, HoleRadius
'Create cut-extrude without draft
Part.FeatureManager.FeatureCut3 True, False, False, _
0, 0, HoleDepth, 0.01, True, False, False, False, _
0, 0, False, False, False, False, False, True, True, _
False, False, False, swStartSketchPlane, 0, False
End If
End Sub

2. Click Save CreateCutExtrudeVBA to save the modified code.

3. Click File > Close and Return to SOLIDWORKS.

Testing the Program and Form


Now test the modified program and the form.

1. In the SOLIDWORKS software, select the bottom face of the candlestick holder.

2. Click Run Macro (Macro toolbar).

3. Open CreateCutExtrudeVBA.swp.

4. Enter 20 in Radius.

5. Enter 10 in Depth.

6. Click OK to create a cut-extrude of the specified depth and radius on the bottom face.

7. Repeat steps 1 through 6 to create another cut-extrude on this face. Enter 15 in Radius and 10 in
Depth.

8. Close the part without saving it.

Congratulations! You have completed this tutorial.


Return to the tutorials overview page.

file:///C:/Users/ABDELHAMID/AppData/Local/Temp/~hh4993.htm 13-Aug-24

You might also like