SOLIDWORKS Macro - Create Lofted Cut

17 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 Lofted Cut through SOLIDWORKS VBA Macros in SOLIDWORKS.

We create Lofted Cut in 2 steps.

  1. Select profiles for Lofted cut.
  2. Create Lofted cut feature using InsertCutBlend method.

This method is most updated method, so use this method if you want to create a new Lofted Cut.

Steps To Create Lofted Cut

We use following steps to create Lofted Cut

A. Select Profile for Lofted Cut.

  1. Inform user to select Profile for Lofted Cut.
  2. User select the Profile for Lofted Cut.

B. Repeat the step A until we complete profile selection.

Results We Can Get

We successfully create Lofted Cut feature as a result.

Below image shows the result we get.

lofted-cut-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 Lofted Cut 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 Lofted Cut feature in VBA is given.

Option Explicit

' Create variable for Solidworks application
Dim swApp As SldWorks.SldWorks

' Create variable for Solidworks document
Dim swDoc As SldWorks.ModelDoc2

' Variable for Solidworks Selection Manager
Dim swSelMgr As SldWorks.SelectionMgr

' Array of Solidworks Entities
Dim swObjects(1 To 2) As SldWorks.Entity

' Variable for Solidworks Entity
Dim swObject As SldWorks.Entity

' Variable for Solidworks Lofted Cut feature
Dim swFeature As SldWorks.Feature

' Variable for Solidworks Select Data
Dim swSelData As SldWorks.SelectData


' Lofted Cut program
Sub main()

  ' Setting Solidworks 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
  
  ' Setting Solidworks document variable to opened part 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
  
  ' Set Solidworks Selection Manager variable
  Set swSelMgr = swDoc.SelectionManager
    
  ' Local variable for selection
  Dim selectItems As Integer
  selectItems = 1
  
  ' Loop till we select all entities
  While selectItems <= 2
      
    ' Message to show user
    Dim messageToUser As String

    ' Update Messages
    Select Case selectItems
      Case 1
        messageToUser = "Please select Profile 1 Sketch from Feature tree for Lofted Cut."
      Case 2
        messageToUser = "Please select Profile 2 Sketch from Feature tree for Lofted Cut."
      Case Else
        Exit Sub
    End Select
  
    ' Show message to user
    MsgBox messageToUser
      
    ' Loop until we complete our selection
    While swObjects(selectItems) Is Nothing
        
      ' Local integer for loop
      Dim i As Integer
      
      ' Loop until we select
      For i = 1 To swSelMgr.GetSelectedObjectCount2(-1)
          
        ' If the profile sketch is selected
        If swSelMgr.GetSelectedObjectType3(i, -1) = swSelectType_e.swSelSKETCHES Then

          ' Set the Solidworks Entity object to profile sketch
          Set swObjects(selectItems) = swSelMgr.GetSelectedObject6(i, -1)
        
        ' If the profile sketch is selected
        ElseIf swSelMgr.GetSelectedObjectType3(i, -1) = swSelectType_e.swSelEXTSKETCHSEGS Then
            
          ' Inform user to select sketch from Tree
          MsgBox "Please select Profile sketches from Feature Tree."
          
          ' Clear selection
          swDoc.ClearSelection2 True
        End If
      Next
      
      DoEvents
    Wend
      
    ' Clear previous selection
    swDoc.ClearSelection2 True
    
    ' Increase the selection count
    selectItems = selectItems + 1

  Wend
    
  ' Local variable for counter
  Dim j As Integer
  j = 1
  
  ' Loop till counter is 2, since we have 2 selection
  While j < 3
  
    ' Set the current instance to Solidworks Entity variable
    Set swObject = swObjects(j)
    
    ' Create Select data for this entity
    Set swSelData = swSelMgr.CreateSelectData
      
    ' For profile, set mark to 1
    swSelData.Mark = 1
    
    ' Select the profile
    swObject.Select4 True, swSelData
        
    j = j + 1
      
  Wend
  
  ' Create Lofted feature
  Set swFeature = swDoc.FeatureManager.InsertCutBlend(False, True, True, 0.01, 0, 0, False, 0, 0, 0, True, True)
  
  ' Check if Lofted Cut Feature creates or not
  If swFeature Is Nothing Then
      MsgBox ("Failed to create Lofted Cut Feature.")
      Exit Sub
  End If
  
  ' Erase array data
  Erase swObjects
  
  ' 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 sketches from code but we use existing sketch to create Lofted Cut feature as shown in below picture.

prerequisite

As shown in above image, there are 2 sketches for Profiles and 1 Extrude feature in our part.

  • Extrude Feature : This is our Extrude part for Lofted Cut feature.
  • Sketch2 : This is our Profile for Lofted Cut feature.
  • Sketch3 : This is also our Profile for Lofted Cut feature.

If you want to create Sketch2 i.e. Profile programmatically then please refer to below articles.

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

For creating Lofted Cut, there are following steps:

  1. Creating Global Variables
  2. Initializing required variables
  3. Ask user to select Profile and Path
  4. Mark selected Entities
  5. Create Lofted Cut Feature
  6. Final work

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

I also give some ๐Ÿ“Œ links 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 Selection Manager
' Variable for Solidworks Selection Manager
Dim swSelMgr As SldWorks.SelectionMgr

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

To see methods and properties related to SldWorks.SelectionMgr object, please visit ๐Ÿ‘‰ this page of SOLIDWORKS API Help.

  • Array of Solidworks Entities
' Array of Solidworks Entities
Dim swObjects(1 To 2) As SldWorks.Entity

In this line, we create an Array of SOLIDWORKS Entities which we named as swObjects and the type of this SldWorks.Entity variable is SldWorks.Entity.

This array consist two SldWorks.Entity variables.

We define the number of variable this array holds inside (1 To 2).

For more information about the Arrays in VBA please ๐Ÿ‘‰ Array on this website.

  • Variable for Solidworks Entity
' Variable for Solidworks Entity
Dim swObject As SldWorks.Entity

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

We create variable swObject for SOLIDWORKS Entities (Profile and Path) we ask use to select.

To see methods and properties related to SldWorks.Entity object, please visit ๐Ÿ‘‰ this page of SOLIDWORKS API Help.

  • Variable for Solidworks Lofted feature
' Variable for Solidworks Lofted Cut feature
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 Lofted Cut Feature.

To see methods and properties related to Feature object, please visit ๐Ÿ‘‰ this page of SOLIDWORKS API Help.

  • Variable for Solidworks Select Data
' Variable for Solidworks Select Data
Dim swSelData As SldWorks.SelectData

In this line, we create a variable named swSelData as SldWorks.SelectData object type.

We create variable swSelData for SOLIDWORKS Select Data, which we use for Marking selected object.

To see methods and properties related to SldWorks.SelectData object, please visit ๐Ÿ‘‰ this page of SOLIDWORKS API Help.

These all are our global variables.

They are SOLIDWORKS API Objects.

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

' Lofted Cut program
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.

  • Set SOLIDWORKS Selection Manager variable
' Set SOLIDWORKS Selection Manager variable
Set swSelMgr = swDoc.SelectionManager

In above line, we set SOLIDWORKS Selection ManagerswSelMgr variable to current documentโ€™s Selection Manager.

  • Local variable for User selection
' Local variable for selection
Dim selectItems As Integer
selectItems = 1

In above line of code, we define a Local variable name selectItemsas Integer type.

In next line we assign a value of 1.

Ask user to select Profiles for Lofted Cut

Now we will ask user to select Profiles for Lofted Cut feature.

Please follow steps given below.

' Loop till we select all entities
While selectItems <= 2

Wend

In above line of code we start a While loop.

For more details about While loop, please see ๐Ÿ‘‰ VBA Looping article from this website.

We want to loop until selectItems variableโ€™s value is equal to 2.

' Message to show user
Dim messageToUser As String

In above line of code we create a variable named messageToUser of String type.

This variable holds the message we want to show before selection.

' Update Messages
Select Case selectItems
  Case 1
    messageToUser = "Please select Profile 1 Sketch from Feature tree for Lofted Cut."
  Case 2
    messageToUser = "Please select Profile 2 Sketch from Feature tree for Lofted Cut."
  Case Else
    Exit Sub
End Select

In above line of code, we use a Select statement to update message.

We use the case on selectItems

When selectItems = 1 then value of messageToUser update to "Please select Profile 1 Sketch from Feature tree for Lofted Cut."

Similarly, when selectItems = 2 then value of messageToUser update to "Please select Profile 2 Sketch from Feature tree for Lofted Cut."

' Show message to user
MsgBox messageToUser

In above line of code, we show the message to user.

Below image show the message to the user.

message-to-select-profile1

' Loop until we complete our selection
While swObjects(selectItems) Is Nothing
    
Wend

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

This loops until we select the our Profile and Path.

For more details about While loop, please see ๐Ÿ‘‰ VBA Looping article from this website.

' Local integer for loop
Dim i As Integer

In above line of code, we create a local integer name i as a counter.

' Loop until we select
For i = 1 To swSelMgr.GetSelectedObjectCount2(-1)

Next

In above line of code, we create a For loop.

This code loops from i = 1 to number of objects we select.

' If the profile sketch is selected
If swSelMgr.GetSelectedObjectType3(i, -1) = swSelectType_e.swSelSKETCHES Then

  ' Set the Solidworks Entity object to profile sketch
  Set swObjects(selectItems) = swSelMgr.GetSelectedObject6(i, -1)

' If the profile sketch is selected
ElseIf swSelMgr.GetSelectedObjectType3(i, -1) = swSelectType_e.swSelEXTSKETCHSEGS Then

  ' Inform user to select sketch from Tree
  MsgBox "Please select Profile sketch from Feature Tree."

  ' Clear selection
  swDoc.ClearSelection2 True
End If

In above line of code, we use ๐Ÿ‘‰ IF/Else statement with conditions.

The ๐Ÿ‘‰ IF statement is True when selected object is type of SOLIDWORKS Sketch.

Similarly, ๐Ÿ‘‰ Else statement is True when select object is type of SOLIDWORKS External Sketch Segment.

When we select the sketch from Model view, then selected object is SOLIDWORKS External Sketch Segment.
When we select the sketch from Feature Tree, then select object is SOLIDWORKS Sketch.

When ๐Ÿ‘‰ IF statement is True we execute code given below.

' Set the Solidworks Entity object to profile sketch
Set swObjects(selectItems) = swSelMgr.GetSelectedObject6(i, -1)

In above line, we set the indexed object inside array.

  • Array of SOLIDWORKS Entities = swObjects
  • Indexed Entity Object = swObjects[selectItems]

We set the value of this Indexed Entity Object by GetSelectedObject6() method of SOLIDWORKS Selection Manager.

When we set the Indexed Entity Object value as Profiles, we exit the 2nd While loop.

When we select both Profiles, then we exit all While loops also.

Similarly, when ๐Ÿ‘‰ Else statement is True we execute code given below.

' Inform user to select sketch from Tree
MsgBox "Please select Profile sketches from Feature Tree."

' Clear selection
swDoc.ClearSelection2 True
  1. We show message to user to select Profile Sketch from Feature Tree.
  2. After that we clear our selection.

We do this because if selected object type is SOLIDWORKS External Sketch Segment then we can not assign this object as SOLIDWORKS Entity inside array.

After For loop, we have a call for DoEvents function.

This function repeats the While loop until we select the Profile or Path.

' Clear previous selection
swDoc.ClearSelection2 True

' Increase the selection count
selectItems = selectItems + 1

In above line, when we finished with the Profile or Path selection, we clear previous selection and increment the selected count by 1.

After increment the selected count we continue our while loop.

Mark selected Entities

Till now we have completed our selection.

Now we need to do Select and Mark entities correctly from our Array.

' Local variable for counter
Dim j As Integer
j = 1

In above line of code we create integer variable for counter.

' Loop till counter is 2, since we have 2 selection
While j < 3

Wend

In above line of code we create a while loop with condition that counter value of j should be less than 3.

' Set the current instance to Solidworks Entity variable
Set swObject = swObjects(j)

In above line of code, we set the SOLIDWORKS Entity variable to current object from array.

' Create Select data for this entity
Set swSelData = swSelMgr.CreateSelectData

In above line of code, we create SOLIDWORKS Select Data for current SOLIDWORKS Entity object.

' For profile, set mark to 1
swSelData.Mark = 1

In above lines, we update the Mark to 1 for our SOLIDWORKS Select Data variable.

For Lofted Cut feature, Mark values can be follows:

  • If a sketch profile, use Mark = 1 .
  • If a guide curve is given, use Mark = 2 .
  • If a centerline is given, use Mark = 4 .

For more details about Mark values for Lofted Cut ๐Ÿ‘‰ please visit this page of SOLIDWORKS API Help.

' Select the profile
swObject.Select4 True, swSelData

In above line of code, we select the Profile object.

We select it by using Select4 method of SOLIDWORKS Entity object.

This method takes 2 arguments.

  1. Append - True appends the entity to the selection list, False replaces the selection list with this entity.
  2. Data - Pointer to the ISelectData object.

We use following values as parameter.

  1. Append - True
  2. Data - swSelData
j = j + 1

After Select statement, we increment the counter variable j by 1.

Create Lofted Cut Feature

We have completed our selection and Marking of SOLIDWORKS Entities.

Now we create Lofted Cut Feature.

' Create Lofted feature
Set swFeature = swDoc.FeatureManager.InsertCutBlend(False, True, True, 0.01, 0, 0, False, 0, 0, 0, True, True)

In above line of code we set the value of variable swFeature by InsertCutBlend method.

This CreateFeature method takes following parameters as explained:

  • Closed - True if you want the loft to be closed, False to leave it open.

  • KeepTangency - Controls whether the section curves are tangent.

  • ForceNonRational - True to force the resulting surface to be non-rational; False to not.

  • TessToleranceFactor - A factor to control the number of intermediate sections used for loft with centerline; the default value is 1.0; the greater the variable, the more intermediate sections are created.

  • StartMatchingType - Tangency type at the start profile.

  • EndMatchingType - Tangency type at the end profile.

  • IsThinBody - True if this feature is a thin body, False is not.

  • Thickness1 - Thickness value for the first direction.

  • Thickness2 - Thickness value for the second direction.

  • ThinType - Thin wall type are as follows.

    Member Description
    One direction 0
    One direction reverse 1
    Mid-plane 2
    Two direction 3
  • UseFeatScope - True if the feature only affects selected bodies, False if the feature affects all bodies.

  • UseAutoSelect - True to automatically select all bodies and have the feature affect those bodies, False to select the bodies the feature affects.

Return Value : This InsertCutBlend method return feature data object.

To see methods and properties related to Feature object, please visit ๐Ÿ‘‰ this page of SOLIDWORKS API Help.

In our code, I have used following values:

Parameter Name Value Used
Closed False
KeepTangency True
ForceNonRational True
TessToleranceFactor 0.01
StartMatchingType 0
EndMatchingType 0
IsThinBody False
Thickness1 0
Thickness2 0
ThinType 0
UseFeatScope True
UseAutoSelect True

InsertCutBlend 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.

' Check if Lofted Cut Feature creates or not
If swFeature Is Nothing Then
  MsgBox ("Failed to create Lofted Cut Feature.")
  Exit Sub
End If

In above line of code, we use an ๐Ÿ‘‰ IF statement to check if we able to create Lofted Cut 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.

lofted-cut-final-result

Final work

After creating Lofted Cut feature, we have to do some cleaning work so that we can use this macro frequently.

  • Empty SOLIDWORKS Entity Array
' Erase array data
Erase swObjects

In above line, we erase data from SOLIDWORKS Entity array.

For this we use Erase function in-build in VBA.

  • 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 Lofted Cut 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: