Solidworks VBA Macro - Create Sketch Driven Pattern

18 minute read

This post has β€œbeginner ➑ intermediate” level Macro program.
If you are following my articles then will not be an issue for you.
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

In this article we create and understand VBA macro of Sketch Driven pattern feature in SOLIDWORKS CAD Software.

This method is most updated method, so use this method if you want to create a new Sketch Driven pattern Feature quickly.

Results We Can Get

After running our macro we successfully create Sketch Driven pattern feature as a result.

Below image shows the result we get.

Sketch-Driven-pattern-final-result

We create Sketch Driven pattern Feature in following steps in general.

  1. Ask user to select a Feature.
  2. Ask user to select a Sketch.

To get the correct result please follow the steps correctly.

Macro Video

Below 🎬 video shows Sketch Driven pattern feature from SOLIDWORKS VBA Macros.


Above video is just for visualization and there are no explanation.

I have explained each and every line in this article.

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

VBA Macro

Below is the VBA macro for creating Sketch Driven pattern Feature.

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

' Variable for Solidworks Entity
Dim swObject As SldWorks.Entity

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

' Variable for Solidworks Sketch Pattern Feature data
Dim swLocalSketchPatternFeat As SldWorks.SketchPatternFeatureData

' Variable for Solidworks Sketch Driven Pattern feature
Dim swFeature As SldWorks.Feature

' Sketch Driven Pattern 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
  
  ' Array of Solidworks Entities
  Dim swObjects(1 To 2) As SldWorks.Entity
    
  ' 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 a Feature for Pattern."
      Case 2
        messageToUser = "Please select a sketch for Pattern."
      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)
      
        Select Case selectItems
          
          Case 1
            ' If the feature is selected
            If swSelMgr.GetSelectedObjectType3(i, -1) = swSelectType_e.swSelBODYFEATURES 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.swSelFACES Then

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

              ' Clear selection
              swDoc.ClearSelection2 True
            End If
          Case 2
            ' If the sketch is selected
            If swSelMgr.GetSelectedObjectType3(i, -1) = swSelectType_e.swSelSKETCHES Then
  
              ' Set the Solidworks Entity object to sketch
              Set swObjects(selectItems) = swSelMgr.GetSelectedObject6(i, -1)
              
            ' If the feature is selected
            ElseIf swSelMgr.GetSelectedObjectType3(i, -1) = swSelectType_e.swSelBODYFEATURES Then
            
              ' Inform user to select sketch from Tree
              MsgBox "Please select Sketch from Feature Tree."

              ' Clear selection
              swDoc.ClearSelection2 True
            
            End If
          
        End Select
        
      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
    
    Select Case j
      Case 1
        ' For feature to mirror, set mark to 1
        swSelData.Mark = 4
      Case 2
        
        ' For sketch, set mark to 64
        swSelData.Mark = 64
    End Select
    
    ' Select the current entity
    swObject.Select4 True, swSelData
    
    j = j + 1
      
  Wend
  
  ' Create Sketch pattern feature data
  Set swLocalSketchPatternFeat = swDoc.FeatureManager.CreateDefinition(swFmSketchPattern)
  
  ' Create Sketch pattern feature
  Set swFeature = swDoc.FeatureManager.CreateFeature(swLocalSketchPatternFeat)
  
  ' Check if Sketch pattern Feature creates or not
  If swFeature Is Nothing Then
    MsgBox ("Failed to create Sketch pattern 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.

  • Knowledge of VBA programming language is ❗required.
  • We are not creating feature from code but we use existing πŸš€ Extrude feature and πŸš€ Sketch Points to create Sketch Driven pattern feature.

Below image shown prerequisite 3D model for our demo.

prerequisite

As shown in above image, there are 2 Extrude features in our part.

  • Base Feature : This is our Base Extrude feature.
  • Feature To Pattern : This is our feature for pattern.

If you want to create these Extrude features and Sketch Points programmatically then please refer to below article.

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

Steps To Follow

This Sketch Driven pattern Feature VBA macro can be divided into following sections:

  1. Creating Global Variables
  2. Initializing required variables
  3. Ask user to select feature and directions
  4. Mark selected entities
  5. Create πŸš€ Sketch Driven Pattern feature Definition
  6. Create Sketch Driven Pattern feature using πŸš€ Sketch Driven Pattern feature Definition.
  7. Final work

Every section with each line is explained below.

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
' Variable for Solidworks application
Dim swApp As SldWorks.SldWorks
  • Purpose: In above line, we create a variable for Solidworks application.
  • Variable Name: swApp
  • Type: SldWorks.SldWorks
  • Reference: Please visit πŸš€ online SOLIDWORKS API Help.
' Variable for Solidworks document
Dim swDoc As SldWorks.ModelDoc2
  • Purpose: In above line, we create a variable for Solidworks document.
  • Variable Name: swDoc
  • Type: SldWorks.ModelDoc2
  • Reference: Please visit πŸš€ online SOLIDWORKS API Help.
' Variable for Solidworks Selection Manager
Dim swSelMgr As SldWorks.SelectionMgr
  • Purpose: In above line, we create a variable for Solidworks Selection Manager.
  • Variable Name: swSelMgr
  • Type: SldWorks.SelectionMgr.
  • Reference: Please visit πŸš€ online SOLIDWORKS API Help.
' Variable for Solidworks Entity
Dim swObject As SldWorks.Entity
  • Purpose: In above line, we create a variable for selection and marking of Solidworks Entity.
  • Variable Name: swObject
  • Type: SldWorks.Entity
  • Reference: Please visit πŸš€ online SOLIDWORKS API Help.
' Variable for Solidworks Select Data
Dim swSelData As SldWorks.SelectData
  • Purpose: In above line, we create a variable for Marking of Solidworks Select Data.
  • Variable Name: swSelData
  • Type: SldWorks.SelectData
  • Reference: Please visit πŸš€ online SOLIDWORKS API Help.
' Variable for Solidworks Sketch Driven Pattern Feature data
Dim swLocalSketchPatternFeat As SldWorks.SketchPatternFeatureData
' Variable for Solidworks Sketch Driven pattern Feature
Dim swFeature As SldWorks.Feature
  • Purpose: In above line, we create a variable for Solidworks Sketch Driven pattern Feature.
  • Variable Name: swFeature
  • Type: SldWorks.Feature
  • Reference: Please visit πŸš€ online SOLIDWORKS API Help.

These all are our global variables.

They are SOLIDWORKS API Objects.

' Sketch Driven Pattern program
Sub main()

End Sub
  • In above line, we create main program for Sketch Driven pattern feature.
  • This is a Sub procedure which has name of main.
  • This procedure hold all the statements (instructions) we give to computer.
  • Reference: Detailed information πŸš€ VBA Sub and Function Procedures article of this website.

Initializing Required Variables

Inside this section we initialize required variables.

' Setting Solidworks variable to current application
Set swApp = Application.SldWorks
  • In above line, we set value of swApp variable.
  • This value is currently opened 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 code block, we check if we successfully set the value of swApp variable.
  • We use πŸš€ IF statement for checking.
  • Condition: swApp Is Nothing
  • When this condition is True,
    • We show and πŸš€ message window to user.
    • Message: SOLIDWORKS is not opened
    • Then we stop our macro here.
' Setting Solidworks document variable to opened part document
Set swDoc = swApp.ActiveDoc
  • In above line, we set value of swDoc variable.
  • This value is currently opened 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 code block, we check if we successfully set the value of swDoc variable.
  • We use πŸš€ IF statement for checking.
  • Condition: swDoc Is Nothing
  • When this condition is True,
    • We show and πŸš€ message window to user.
    • Message: Solidworks document is not opened. Please open a document.
    • Then we stop our macro here.
' Set Solidworks Selection Manager variable
Set swSelMgr = swDoc.SelectionManager
  • In above line, we set value of swSelMgr variable.
  • This value is current document’s Selection Manager.
' Array of Solidworks Entities
Dim swObjects(1 To 2) As SldWorks.Entity
  • In above line, we create an πŸš€ Array of Solidworks Entities.
  • Variable Name: swObjects
  • Type: SldWorks.Entity
  • Length of Array: (1 To 2)
  • Reference: Please visit
' Local variable for selection
Dim selectItems As Integer
selectItems = 1
  • In above line, we create a variable for selection and set its value.
  • Variable Name: selectItems
  • Type: Integer
  • Value: 1

Ask user to select feature and directions

In this section, we ask user to select Feature and Sketch for Sketch Driven Pattern feature.

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

Wend
  • In above line of code we start a While loop.
  • We loop until selectItems variable’s value is equal to 2.
  • Reference: πŸš€ VBA Looping article from this website.
' Message to show user
Dim messageToUser As String
  • In above line, we create a variable to show a messages we want to show before selection.
  • Variable Name: messageToUser
  • Type: String
' Update Messages
Select Case selectItems
  Case 1
    messageToUser = "Please select a Feature for Pattern."
  Case 2
    messageToUser = "Please select a sketch for Pattern."
  Case Else
    Exit Sub
End Select
  • In above code block, we use a Select statement to update message.
  • We use the case on selectItems.
    • Case 1: messageToUser update to "Please select a Feature for Pattern."
    • Case 2: messageToUser update to "Please select a sketch for Pattern."
  • Reference: πŸš€ Select statement article of this website.
' Show message to user
MsgBox messageToUser
  • In above line, we show the message to user.
  • Below image shows the message for Feature selection to the user.

message-to-select-feature-for-sketch-driven-pattern

  • Below image shows the message for Sketch selection to the user.

message-to-select-sketch-for-sketch-driven-pattern

' Loop until we complete our selection
While swObjects(selectItems) Is Nothing
    
Wend
  • In above line, we create another While loop.
  • This loops continues to run until we select the our Feature and Edge for circular pattern.
  • Reference: πŸš€ VBA Looping article from this website.
' Local integer for loop
Dim i As Integer
  • In above line, we create a variable as a counter.
  • Variable Name: i
  • Type: Integer
' Loop until we select
For i = 1 To swSelMgr.GetSelectedObjectCount2(-1)

Next
  • In above line, we create a For loop.
  • This loops start from i = 1 to number of objects we select.
' Update Messages
Select Case selectItems

End Select
  • In above line, we use a Select statement for selection entities.
  • We use the case on selectItems.
  • Reference: πŸš€ Select statement article of this website.
Case 1
	' If the profile sketch is selected
  If swSelMgr.GetSelectedObjectType3(i, -1) = swSelectType_e.swSelBODYFEATURES Then

    ' Set the Solidworks Entity object to feature for Linear pattern
    Set swObjects(selectItems) = swSelMgr.GetSelectedObject6(i, -1)

    ' If the face is selected
  ElseIf swSelMgr.GetSelectedObjectType3(i, -1) = swSelectType_e.swSelFACES Then

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

    ' Clear selection
    swDoc.ClearSelection2 True
  End If
  • Above code block we use for Case 1.
  • In above code block, we use πŸš€ IF/ElseIf statement with conditions.
  • The πŸš€ IF statement is True when selected object is type of SOLIDWORKS Body Feature.
  • Similarly, πŸš€ ElseIf statement is True when select object is type of SOLIDWORKS Face.

When we select the sketch from Model view, then selected object is SOLIDWORKS Face.
When we select the sketch from Feature Tree, then select object is SOLIDWORKS Body Feature.

' Set the Solidworks Entity object to feature for Linear pattern
Set swObjects(selectItems) = swSelMgr.GetSelectedObject6(i, -1)
  • When πŸš€ IF statement is True we run above line.
  • In above line, we set the object inside array.
    • Array of SOLIDWORKS Entities = swObjects
    • Indexed Entity Object = swObjects[selectItems]
  • Indexed Entity Object value set by GetSelectedObject6() method.
    • GetSelectedObject6() method is part of SOLIDWORKS Selection Manager.
    • Reference: Please visit πŸš€ online Solidworks API Help.
' Inform user to select feature from Feature Tree
MsgBox "Please select feature from Feature Tree."

' Clear selection
swDoc.ClearSelection2 True
  • When πŸš€ ElseIf statement is True we execute run above lines.
  • 1st Line: We show a message to user to select Feature from Feature Tree.
  • 2nd Line: After that we clear our selection.

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

Case 2
  ' If the sketch is selected
  If swSelMgr.GetSelectedObjectType3(i, -1) = swSelectType_e.swSelSKETCHES Then
  
    ' Set the Solidworks Entity object to sketch
    Set swObjects(selectItems) = swSelMgr.GetSelectedObject6(i, -1)
	
  ' If the feature is selected
  ElseIf swSelMgr.GetSelectedObjectType3(i, -1) = swSelectType_e.swSelBODYFEATURES Then
    ' Inform user to select sketch from Tree
    MsgBox "Please select Sketch from Feature Tree."

    ' Clear selection
    swDoc.ClearSelection2 True
  End If
  • Above code block we use for Case 2.
  • In above line, we use πŸš€ IF/ElseIf statement with conditions.
  • πŸš€ IF statement is True when selected object is type of SOLIDWORKS Sketch.
  • Similarly, πŸš€ ElseIf statement is True when select object is type of SOLIDWORKS Body.
' Set the Solidworks Entity object to selected sketch
Set swObjects(selectItems) = swSelMgr.GetSelectedObject6(i, -1)
  • When πŸš€ IF statement is True we execute code given below.
  • In above line, we set the indexed object inside array.
    • Array of SOLIDWORKS Entities = swObjects
    • Indexed Entity Object = swObjects[selectItems]
  • Indexed Entity Object value set by GetSelectedObject6() method.
    • GetSelectedObject6() method is part of SOLIDWORKS Selection Manager.
    • Reference: Please visit πŸš€ online Solidworks API Help.
' Inform user to select sketch from Tree
MsgBox "Please select Sketch from Feature Tree."

' Clear selection
swDoc.ClearSelection2 True
  • When πŸš€ ElseIf statement is True we execute code given below.
  • 1st Line: We show a message to user to select Sketch.
  • 2nd Line: We clear our selection.
DoEvents
  • After For loop end, we have a call for DoEvents function.
  • This function repeats the While loop until we complete Feature or Sketch selection.
' Clear previous selection
swDoc.ClearSelection2 True

' Increase the selection count
selectItems = selectItems + 1
  • 1st Line: We clear previous selection.
  • 2nd Line: Increment the selectItems count by 1.

After increment the selected count we continue our while loop.

Mark selected Entities

In previous section, we complete our selection.

In this section, we complete Select and Mark entities correctly from our Array.

' Local variable for counter
Dim j As Integer
j = 1
  • In above line, we create a variable as a counter.
  • Variable Name: j
  • Type: Integer
  • Value: 1
' Loop till counter is 2, since we have 2 selection
While j < 3

Wend
  • In above line, we create a while loop.
  • Condition: that counter value of j should be less than 3.
  • Reference: πŸš€ VBA Looping article from this website.
' Set the current instance to Solidworks Entity variable
Set swObject = swObjects(j)
  • In above line, we set the SOLIDWORKS Entity variable to current object from array.
' Create Select data for this entity
Set swSelData = swSelMgr.CreateSelectData
  • In above line, we create SOLIDWORKS Select Data for current SOLIDWORKS Entity object.
' Update Messages
Select Case j

End Select
  • In above line of code, we use a Select statement for selection entities.
  • We use the case on j.
  • Reference: πŸš€ Select statement article of this website.
Case 1
  ' For feature to pattern, set mark to 4
  swSelData.Mark = 4
  • Above code block, we use for Case 1.
  • In above lines, we set Mark to 4.
  • For Sketch Driven Pattern feature, Mark values can be follows:
Any… Must be preselected and marked with a value of…
Feature 4
Points 32
Sketches 64
Faces 128
Bodies 256
Case 2
  ' For sketch, set mark to 64
  swSelData.Mark = 64
  • Above code sample we use for Case 2.
  • In above lines, we update the Mark to 64.
  • For Sketch Driven Pattern feature, Mark values can be follows:
Any… Must be preselected and marked with a value of…
Feature 4
Points 32
Sketches 64
Faces 128
Bodies 256
' Select the current entity
swObject.Select4 True, swSelData
  • In above line, we select the object.
  • We select it by using Select4 method of SOLIDWORKS Entity object.
  • This method takes 2 arguments.
    • Append - True appends the entity to the selection list, False replaces the selection list with this entity.
    • Data - Pointer to the ISelectData object.
  • We use following values as parameter.
    • Append - True
    • Data - swSelData
j = j + 1

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

Create Sketch Driven Pattern Feature Definition

In this section we create πŸš€ Sketch Driven Pattern feature Definition and set its properties for Sketch Driven Pattern.

' Create Sketch pattern feature data
Set swLocalSketchPatternFeat = swDoc.FeatureManager.CreateDefinition(swFmSketchPattern)
  • In above line of code we set the value of variable swLocalSketchPatternFeat by CreateDefinition method.
  • CreateDefinition method is part of FeatureManager object.
  • 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 return feature or pattern-specific feature data object.
  • In our code, I have used following values:
    • Type - I use swFmSketchPattern as Feature name ID.

Reference: For more details about

Create Sketch Driven Pattern

In this section, we create Sketch Driven Pattern.

' Create Sketch pattern feature
Set swFeature = swDoc.FeatureManager.CreateFeature(swLocalSketchPatternFeat)
  • In above line, we set the value of variable swFeature 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.
  • Reference: πŸš€ online Solidworks API Help for Solidworks Feature Manager FeatureManager.

  • In our code, I have used following values:
    • FeatureData - I use swLocalSketchPatternFeat as feature data object which we defined previously.
' Check if Sketch pattern Feature creates or not
If swFeature Is Nothing Then
  MsgBox ("Failed to create Sketch pattern Feature.")
  Exit Sub
End If
  • In above code block, we check if we successfully create πŸš€ Sketch Driven Pattern Feature or not.
  • We use πŸš€ IF statement for checking.
  • Condition: swFeature Is Nothing
  • When this condition is True,
    • We show and πŸš€ message window to user.
    • Message: Failed to create Circular Pattern.
    • Then we stop our macro here.

Sketch-Driven-pattern-final-result

Final work

In this section, after creating Sketch Driven Pattern feature, we have to do some cleaning work so that we can use this macro frequently.

' 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.
' 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 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 Sketch Driven Pattern feature with SOLIDWORKS VBA Macros.

For more such tutorials on SOLIDWORKS VBA Macro, do come to this website 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!!!