SOLIDWORKS Macro - Create Threads

15 minute read

This article is an "Intermediate" post and required you to have some knowledge of VBA.
If you are following my articles you will notice that till now we were hardcoding the selections for input parameters.
But from this post onward we will take user-inputs.
In this article we did not use 🚀 UserForm for taking inputs, instead we use 🚀 Input Box for value input and 🚀 Message Box to notify user.
I hope you will also like this type of tutorials.
Thank you for reading.

Objective

Objective of this article is to learn how to create 👉 Thread Feature through SOLIDWORKS VBA Macros in SOLIDWORKS.

We create Thread Feature in 3 steps in general.

  1. Traversing through Feature Tree.
  2. Programmatically select a 👉 Feature from Feature Tree named Cylinder.
  3. Get Cylinder surface of 👉 Feature.
  4. Create 👉 Thread Feature Definition.
  5. Create 👉 Thread Feature using 👉 Thread Feature Definition from method CreateFeature.

This method is most updated method, so use this method if you want to create a new 👉 Thread Feature.

Steps To Create Thread

We use following steps to create 👉 Thread Feature while writing macro

  1. Traversing through Feature Tree.
  2. Programmatically select a 👉 Feature from Feature Tree named Cylinder.
  3. Get all Faces of Cylinder.
  4. Get Cylinder 👉 Surface of selected 👉 Feature.
  5. Select the top 👉 Edge of Cylinder 👉 Surface.
  6. Create 👉 Thread Feature Definition.
  7. Create 👉 Thread Feature using 👉 Thread Feature Definition from method CreateFeature.

Results We Can Get

After running our we successfully create Hole feature as a result.

Below image shows the result we get.

threads-final-result

To get the correct result please follow the steps correctly.

Video of Code on YouTube

Please see below 🎬 video on how to create Thread feature from SOLIDWORKS VBA Macros.


Please note that there are no explanation in the video.

Explanation of each line and why we write code this way is given in this post.

It is advisable to watch video, since it help you to better understand the process.

Code Sample

Below is the code for creating Thread Feature feature in VBA is given.

Option Explicit

' Solidworks application variable
Dim swApp As SldWorks.SldWorks

' Solidworks document variable
Dim swDoc As SldWorks.ModelDoc2

' Solidworks Thread feature data variable
Dim swThreadFeatData As SldWorks.ThreadFeatureData

' Solidworks Thread Feature variable
Dim swThreadFeature As SldWorks.Feature

' Solidworks Feature variable
Dim swFeature As SldWorks.Feature

' Solidworks Face variable
Dim swFace As SldWorks.Face2

' Solidworks Surface variable
Dim swSurface As SldWorks.Surface

' Solidworks Entity variable
Dim swEnt As SldWorks.Entity

' Variable for Solidworks Edges
Dim swEdges As Variant

' Solidworks Edge variable
Dim swEdge As SldWorks.Edge

' Array for Solidworks Faces
Dim faceArray As Variant

' Variable for Solidworks Face
Dim eachFace As Variant

' Boolean variable
Dim boolStatus As Boolean

' Main program for Thread
Sub main()

  ' Set Solidworks application variable to current application
  Set swApp = Application.SldWorks
  
  ' Check if Solidworks is opened or not
  If swApp Is Nothing Then
    MsgBox ("Solidworks is not opened")
    Exit Sub
  End If
  
  ' Set Solidworks document variable to open document
  Set swDoc = swApp.ActiveDoc
  
  ' Check if Solidworks document is opened or not
  If swDoc Is Nothing Then
    MsgBox ("Solidworks document is not opened. Please open a document.")
    Exit Sub
  End If
  
  ' Get First feature in Feature tree
  Set swFeature = swDoc.FirstFeature
  
  ' Check if Solidworks document is selected or not
  If swFeature Is Nothing Then
    MsgBox ("Failed to selected First feature in Feature Tree.")
    Exit Sub
  End If
  
  ' Traversing through the Feature Tree,
  ' until Feature name is "Cylinder"
  While swFeature.Name <> "Cylinder"
    
    ' Print current Feature name is Immediate window
    Debug.Print swFeature.Name
    
    ' Get the next feature
    Set swFeature = swFeature.GetNextFeature
  Wend
  
  ' Print current Feature name is Immediate window
  Debug.Print swFeature.Name
  
  ' Get the faces of selected feature
  faceArray = swFeature.GetFaces

  ' Loop through all Face array
  For Each eachFace In faceArray
  
    ' Set Solidworks Face variable to current current
    Set swFace = eachFace
    
    ' Get the Surface of from the Solidworks Face variable
    Set swSurface = swFace.GetSurface
    
    ' If we have cylinder surface
    If swSurface.IsCylinder() Then
    
      ' Get all edges of this face
      swEdges = swFace.GetEdges
      
      ' Set Solidworks edge variable to 1st edge
      Set swEdge = swEdges(0)
      
      ' Set Solidworks Entity variable to Solidworks Edge variable
      Set swEnt = swEdge
      
      ' Select the current entity
      boolStatus = swEnt.Select(True)
      
      ' If fail to select the edge then inform user
      If boolStatus = False Then
        MsgBox "Failed to select Edge of Cylinder."
        Exit Sub
      End If
      
    End If
  Next
  
  ' Create Thread feature data
  Set swThreadFeatData = swDoc.FeatureManager.CreateDefinition(swFeatureNameID_e.swFmSweepThread)
  
  ' Create Thread Feature
  Set swThreadFeature = swDoc.FeatureManager.CreateFeature(swThreadFeatData)
  
  ' Check if Thread Feature created or not
  If swThreadFeature Is Nothing Then
    MsgBox ("Failed to create Thread Feature.")
    Exit Sub
  End If
  
  ' View zoom to fit
  swDoc.ViewZoomtofit2
  
  ' Clear all selection
  swDoc.ClearSelection2 True
    
End Sub

Prerequisite

There are some prerequisite for this article.

We are not creating feature from code but we use existing feature to create 👉 Thread Feature as shown in below picture.

prerequisite

As shown in above image, there only 1 Extrude feature in our part.

If you want to create Extrude feature programmatically then please refer to below article.

Also, we will apply checks in this article, so the code we write should be error free most of the time.

Steps To Follow

To create 👉 Thread Feature, there are following steps:

  1. Creating Global Variables
  2. Initializing required variables
  3. Get Cylinder Feature by Traversing Feature Tree
  4. Select top edge of Cylinder Feature
  5. Create Thread feature using Thread Feature Data
  6. Final work

Now let us walk through each step as given above, and understand every line.

I also give some links (see icon 👉 ) so that you can go through them if there are anything I explained in previous articles.

Creating Global Variables

Option Explicit

This line forces us to define every variable we are going to use.

For more information please visit 👉 SOLIDWORKS Macros - Open new Part document post.

We create following variables.

  • Variable for Solidworks application
' Variable for Solidworks application
Dim swApp As SldWorks.SldWorks

In this line, we create a variable which we named as swApp and the type of this swApp variable is SldWorks.SldWorks.

To see methods and properties related to SldWorks.SldWorks object, please visit 👉 this page of SOLIDWORKS API Help.

  • Variable for Solidworks document
' Variable for Solidworks document
Dim swDoc As SldWorks.ModelDoc2

In this line, we create a variable which we named as swDoc and the type of this swDoc variable is SldWorks.ModelDoc2.

To see methods and properties related to SldWorks.ModelDoc2 object, please visit 👉 this page of SOLIDWORKS API Help.

  • Variable for Solidworks Thread feature data
' Solidworks Thread feature data variable
Dim swThreadFeatData As SldWorks.ThreadFeatureData

In this line, we create a variable which we named as swThreadFeatData and the type of this swThreadFeatData variable is SldWorks.ThreadFeatureData.

To see methods and properties related to SldWorks.ThreadFeatureData object, please visit 👉 this page of SOLIDWORKS API Help.

  • Variable for Solidworks feature
' Solidworks Thread Feature variable
Dim swThreadFeature As SldWorks.Feature

In this line, we Create a variable which we named as swThreadFeature and the type of this swThreadFeature variable is SldWorks.Feature.

We create variable swThreadFeature for SOLIDWORKS Feature.

To see methods and properties related to Feature object, please visit 👉 this page of SOLIDWORKS API Help.

  • Variable for Solidworks Feature variable
' Solidworks Feature variable
Dim swFeature As SldWorks.Feature

In this line, we Create a variable which we named as swFeature and the type of this swFeature variable is SldWorks.Feature.

We create variable swFeature for SOLIDWORKS Feature.

To see methods and properties related to Feature object, please visit 👉 this page of SOLIDWORKS API Help.

  • Variable for Solidworks Face variable
' Solidworks Face variable
Dim swFace As SldWorks.Face2

In this line, we Create a variable which we named as swFace and the type of this swFace variable is SldWorks.Face2.

We create variable swFace for SOLIDWORKS Face.

To see methods and properties related to Face2 object, please visit 👉 this page of SOLIDWORKS API Help.

  • Variable for Solidworks Surface
' Solidworks Surface variable
Dim swSurface As SldWorks.Surface

In this line, we Create a variable which we named as swSurface and the type of this swSurface variable is SldWorks.Surface.

We create variable swSurface for SOLIDWORKS Surface.

To see methods and properties related to Surface object, please visit 👉 this page of SOLIDWORKS API Help.

  • Variable for Solidworks Entity
' Solidworks Entity variable
Dim swEnt As SldWorks.Entity

In this line, we create a variable which we named as swEnt and the type of this swEnt variable is SldWorks.Entity.

We create variable swEnt for SOLIDWORKS Entity.

To see methods and properties related to Entity object, please visit 👉 this page of SOLIDWORKS API Help.

  • Variable for Edges
' Variable for Solidworks Edges
Dim swEdges As Variant

In this line, we create a variable named swEdges as Variant object type.

We create variable swEdges for to get all edges of a surface.

  • Variable for Solidworks Edge
' Solidworks Edge variable
Dim swEdge As SldWorks.Edge

In this line, we create a variable which we named as swEdge and the type of this swEdge variable is SldWorks.Edge.

We create variable swEnt for SOLIDWORKS Edge.

To see methods and properties related to Edge object, please visit 👉 this page of SOLIDWORKS API Help.

  • Array for Solidworks Faces
' Array for Solidworks Faces
Dim faceArray As Variant

In this line, we create a variable named faceArray as Variant object type.

We create variable faceArray for to get all face of Cylinder feature.

  • Variable for Solidworks Face
' Variable for Solidworks Face
Dim eachFace As Variant

In this line, we create a variable named eachFace as Variant object type.

We create variable eachFace for to get each face inside faceArray array.

  • Boolean variable
' Boolean variable
Dim boolStatus As Boolean

In this line, we create a variable named boolStatus as Boolean object type.

We create variable boolStatus to confirm method result.

These all are our global variables.

They are SOLIDWORKS API Objects.

So basically I group all the SOLIDWORKS API Objects in one place.

' Main program for Thread
Sub main()

End Sub

Next is our Sub procedure which has name of main.

This procedure hold all the statements (instructions) we give to computer.

To know more about Sub Procedure you can check 👉 VBA Sub and Function Procedures article of this website.

Initializing Required Variables

Inside this procedure we first initialize required variables as given below.

  • Set SOLIDWORKS variable to SOLIDWORKS application
' Set SOLIDWORKS variable to SOLIDWORKS application
Set swApp = Application.SldWorks

In this line, we set the value of our SOLIDWORKS variable swApp; which we define earlier; to SOLIDWORKS application.

' Check if SOLIDWORKS is opened or not
If swApp Is Nothing Then
  MsgBox ("SOLIDWORKS is not opened")
  Exit Sub
End If

In above line of code, we use an 👉 IF statement to check if SOLIDWORKS application variable is successfully assigned to current SOLIDWORKS application.

  • Set SOLIDWORKS document variable to opened part document
' Set SOLIDWORKS document variable to opened part document
Set swDoc = swApp.ActiveDoc

In above line of code, we set SOLIDWORKS document swDoc variable to currently open part document.

' Check if SOLIDWORKS document is opened or not
If swDoc Is Nothing Then
  MsgBox ("SOLIDWORKS document is not opened. Please open a document.")
  Exit Sub
End If

In above line of code, we use an 👉 IF statement to check if SOLIDWORKS document swDoc is opened.

If SOLIDWORKS document is not opened then code execute inside the code and inform the user by a 👉 Message Window.

Get Cylinder Feature by Traversing Feature Tree

Now we will get Cylinder feature by Traversing Feature Tree.

Please follow steps given below.

  • Get First feature in Feature tree
' Get First feature in Feature tree
Set swFeature = swDoc.FirstFeature

In above line of code, we set SOLIDWORKS Feature swFeature variable to first feature in Feature Tree.

' Check if Solidworks document is selected or not
If swFeature Is Nothing Then
  MsgBox ("Failed to selected First feature in Feature Tree.")
  Exit Sub
End If

In above line of code, we use an 👉 IF statement to check if we get SOLIDWORKS Feature swFeature.

If we failed to get SOLIDWORKS Feature then code execute inside the code and inform the user by a 👉 Message Window.

' Traversing through the Feature Tree,
' until Feature name is "Cylinder"
While swFeature.Name <> "Cylinder"

Wend

In above line of code, we create another While loop.

This loop will continue until we select the our Cylinder 👉 Feature.

For more details about While loop, please see 👉 VBA Looping article from this website.

' Print current Feature name is Immediate window
Debug.Print swFeature.Name

In above line of code, we print 👉 Feature name into Immediate window.

' Get the next feature
Set swFeature = swFeature.GetNextFeature

In above line of code, we set swFeature variable to next 👉 Feature.

' Print current Feature name is Immediate window
Debug.Print swFeature.Name

In above line of code, we print 👉 Feature name into Immediate window.

Since this line is outside of While loop, it means selected feature is Cylinder 👉 Feature.

Select top edge of Cylinder Feature

Now we need to select top edge of previously selected Cylinder 👉 Feature.

Please follow steps given below.

  • Get the faces of selected feature
' Get the faces of selected feature
faceArray = swFeature.GetFaces

In above line of code we get all faces of selected Cylinder 👉 Feature.

  • Loop through all face array
' Loop through all Face array
For Each eachFace In faceArray

Next

In above line of code we create a 👉 For Each loop.

  • Get surface of current Face
' Set Solidworks Face variable to current face
Set swFace = eachFace

In above line of code, we Set 👉 SOLIDWORKS Face variable swFace to current face.

' Get the Surface of from the Solidworks Face variable
Set swSurface = swFace.GetSurface

In above line of code we get the 👉 Surface of from the 👉 SOLIDWORKS Face variable using GetSurface 👉 method.

  • If Statement for Cylindrical Surface
' If we have cylinder surface
If swSurface.IsCylinder() Then

End If

In above line of code, we use an 👉 IF statement to check if 👉 SOLIDWORKS Surface swSurface is Cylindrical Surface or not.

  • Select first edge of Cylindrical Surface
' Get all edges of this face
swEdges = swFace.GetEdges

In above line of code we get all edges of current face.

' Set Solidworks edge variable to 1st edge
Set swEdge = swEdges(0)

In above line of code we set 👉 SOLIDWORKS edge variable swEdge to 1st edge.

' Set Solidworks Entity variable to Solidworks Edge variable
Set swEnt = swEdge

In above line of code we set 👉 SOLIDWORKS Entity variable to 👉 SOLIDWORKS edge variable.

' Select the current entity
boolStatus = swEnt.Select(True)

In above line of code we select the current entity.

' If fail to select the edge then inform user
If boolStatus = False Then
  MsgBox "Failed to select Edge of Cylinder."
  Exit Sub
End If

In above line of code, we use an 👉 IF statement to check if Boolean variable boolStatus is False.

If Boolean variable boolStatus is False. then code execute inside the code and inform the user by a 👉 Message Window.

Create Thread feature using Thread Feature Data

We have completed our selection of 👉 SOLIDWORKS Entity.

Now we create Thread Feature.

For this we use 2 steps as follows:

  1. Create Thread Feature definition
  2. Create Thread Feature using the definition
' Create Thread feature data
Set swThreadFeatData = swDoc.FeatureManager.CreateDefinition(swFeatureNameID_e.swFmSweepThread)

In above line of code we set the value of variable swThreadFeatData by CreateDefinition method.

CreateDefinition method is part of FeatureManager object.

This FeatureManager is again part of swDoc variable i.e. ModelDoc2 object.

This CreateDefinition method takes following parameters as explained:

  • Type - Feature name ID as defined in swFeatureNameID_e.

    • swFmBoundingBox (bounding box)
    • swFmCirPattern (circular pattern)
    • swFmCurvePattern (curve-driven pattern)
    • swFmDerivedLPattern (derived-driven pattern)
    • swFmDimPattern (variable/dimension pattern)
    • swFmFillPattern (fill pattern)
    • swFmGroundPlane (ground plane)
    • swFmLibraryFeature (library)
    • swFmLocalChainPattern (chain component pattern)
    • swFmLocalCirPattern (circular component pattern)
    • swFmLocalCurvePattern (curve-driven component pattern)
    • swFmLocalLPattern (linear component pattern)
    • swFmLocalSketchPattern (sketch-driven component pattern)
    • swFmLPattern (linear pattern)
    • swFmNormalCut (sheet metal normal cut)
    • swFmRefCurve (projection curve)
    • swFmRefSurface (surface sweep)
    • swFmSketchPattern (sketch-driven pattern)
    • swFmSweep (boss sweep)
    • swFmSweepCut (cut sweep)
    • swFmSweepThread (Thread)
    • swFmTabAndSlot (tab and slot)
    • swFmTablePattern (table pattern)

Return Value : This CreateDefinition method retun feature or pattern-specific feature data object.

To see methods and properties related to FeatureManager object, please visit 👉 this page of Solidworks API Help.

In our code, I have used following values:

  • Type - I use swFmSweepThread as Feature name ID.

If you want to know more information about Sweep Feature data then please visit 👉 this page of Solidworks API Help.

This page will give you information about various properties and methods of IThreadFeatureData Interface.

' Create Thread Feature
Set swThreadFeature = swDoc.FeatureManager.CreateFeature(swThreadFeatData)

In above line of code we set the value of variable swThreadFeature by CreateFeature method.

This CreateFeature method takes following parameters as explained:

  • FeatureData - Feature or pattern-specific feature data object.

Return Value : This CreateFeature method return feature data object.

CreateFeature method is part of FeatureManager object.

This FeatureManager is again part of swDoc variable i.e. ModelDoc2 object.

To see methods and properties related to FeatureManager object, please visit 👉 this page of SOLIDWORKS API Help.

In our code, I have used following values:

  • FeatureData - I use swThreadFeatData as feature data object which we defined previously.
' Check if Thread Feature created or not
If swThreadFeature Is Nothing Then
  MsgBox ("Failed to create Thread Feature.")
  Exit Sub
End If

In above line of code, we use an 👉 IF statement to check if we able to create 👉 Thread Feature or not.

If we failed to select then inform the user by a 👉 Message Window.

After showing error message our program exit from here itself.

Now we run the macro and after running macro we get Revolve as shown in below image.

threads-final-result

Final work

After creating 👉 Thread Feature , we have to do some cleaning work so that we can use this macro frequently.

  • Make part Zoom to fit
' View zoom to fit
swDoc.ViewZoomtofit2

In above line, we make our view zoom to fit the model.

For this we use ViewZoomtofit2 method which is part of SOLIDWORKS Document variable i.e swDoc variable.

  • Clear selection
' Clear all selection
swDoc.ClearSelection2 True

In above line, we clear all previous selection.

For this we use ClearSelection2 method which is part of SOLIDWORKS Document variable i.e swDoc variable.

This is it !!!

I hope my efforts will helpful to someone!

If you found anything to add or update, please let me know on my e-mail.

Hope this post helps you to create Threads with SOLIDWORKS VBA Macros.

For more such tutorials on SOLIDWORKS VBA Macro, do come to this blog after sometime.

If you like the post then please share it with your friends also.

Do let me know by you like this post or not!

Till then, Happy learning!!!

Updated: