SolidWorks Automation
8 min read
403

How to Cut-Extrude from Sketch in SolidWorks using VBA macro?

May 31, 2025
0
How to Cut-Extrude from Sketch in SolidWorks using VBA macro?

How to Cut-Extrude from Sketch in SolidWorks using VBA Macro?

Automating your SolidWorks design process can save time, reduce repetitive steps, and boost productivity. In this tutorial, youโ€™ll learn how to create a Cut-Extrude feature from an existing sketch using VBA macro inside SolidWorks.

This step-by-step guide walks you through:

  • โœ… Accessing SolidWorks via VBA

  • โœ… Selecting a sketch

  • โœ… Creating a cut-extrude

  • โœ… Handling errors and validations

Letโ€™s dive in.


๐Ÿงพ Step-by-Step SolidWorks Macro with Comments

Full VBA Code โ€“ With Line-by-Line Explanation

Option Explicit

' Create a variable to store the SolidWorks application object
Dim swApp As SldWorks.SldWorks

' Create a variable for the active document (part/assembly)
Dim swDoc As SldWorks.ModelDoc2

' Create a variable to hold the created feature
Dim swFeature As SldWorks.Feature

' Boolean variable to check status of operations
Dim BoolStatus As Boolean

' Main subroutine starts here
Sub main()

  ' Get the current running SolidWorks instance
  Set swApp = Application.SldWorks
  
  ' Check if SolidWorks is running
  If swApp Is Nothing Then
      MsgBox ("SolidWorks is not opened")
      Exit Sub
  End If
  
  ' Get the currently active document (must be a Part)
  Set swDoc = swApp.ActiveDoc
  
  ' If no document is open, exit the macro
  If swDoc Is Nothing Then
      MsgBox ("SolidWorks document is not opened. Please open a document.")
      Exit Sub
  End If

  ' Attempt to select Sketch2 for extrusion
  BoolStatus = swDoc.Extension.SelectByID2("Sketch2", "SKETCH", 0, 0, 0, False, 0, Nothing, swSelectOption_e.swSelectOptionDefault)

  ' If selection fails, notify user
  If BoolStatus = False Then
      MsgBox ("Failed to select Sketch2.")
      Exit Sub
  End If

  ' Create a cut-extrude through all using selected sketch
  Set swFeature = swDoc.FeatureManager.FeatureCut4( _
      True, False, False, _
      swEndCondThroughAll, 0, _
      0.01, 0.01, _
      False, False, False, False, _
      1, 1, False, False, _
      False, False, False, _
      True, True, True, True, _
      False, swStartSketchPlane, 0, _
      False, False)

  ' If feature creation fails, alert the user
  If swFeature Is Nothing Then
      MsgBox ("Failed to create Extrude Cut Feature.")
      Exit Sub
  End If

End Sub

What Does This Macro Do?

โœ… 1. Gets the active SolidWorks session

It starts by checking if SolidWorks is open and a document is active.

โœ… 2. Selects “Sketch2”

It tries to select a sketch with the name "Sketch2" on the active part.

๐Ÿ’ก Make sure “Sketch2” exists in the part before running the macro.

โœ… 3. Creates a Cut-Extrude

Using FeatureCut4, the macro creates a cut through all from the selected sketch.

โœ… 4. Adds Error Handling

Basic error handling ensures you donโ€™t get stuck if somethingโ€™s missing.


๐Ÿ“Œ Important Notes

  • This macro only works in part documents (.SLDPRT)

  • It requires Sketch2 to be pre-created and fully closed

  • Modify "Sketch2" if your sketch has a different name


๐Ÿ” Example Use Cases

  • Automate repeated cut operations

  • Apply standard cut-outs to imported geometry

  • Pre-process parts for downstream tasks


๐Ÿง  Final Thoughts

This VBA macro is a great example of how automation can simplify design workflows. Whether you’re processing hundreds of models or just saving clicks, a small macro like this can go a long way.

If you’re interested in:

  • Customizing macros

  • Creating sketches programmatically

  • Full part design automation

Let me know โ€” weโ€™re building a full VBA & SolidWorks automation series for The Tech Thinker!

๐Ÿ“ฅ Need Help?

Drop a comment below or contact us for custom macro development. We love building intelligent, reusable design tools!

Cut-Extrude from Sketch in SolidWorks using VBA

Step by Step Detailed Explanation

Step 1: Declare Variables

Option Explicit

Dim swApp As SldWorks.SldWorks              ' SolidWorks application
Dim swDoc As SldWorks.ModelDoc2             ' Active document (Part/Assembly)
Dim swFeature As SldWorks.Feature           ' Stores the created feature
Dim BoolStatus As Boolean                   ' Holds True/False status of operations


Explanation:

We declare the objects weโ€™ll use in the macro โ€” one for the app, one for the document, one for the feature, and a boolean to track success/failure.
This makes the code more readable and easy to debug.

๐Ÿ”น Step 2: Start the Main Procedure

Sub main()

Explanation:
This is the starting point of your macro.
Everything you want to automate goes inside this subroutine.

๐Ÿ”น Step 3: Get SolidWorks Application Instance

Set swApp = Application.SldWorks

If swApp Is Nothing Then
    MsgBox ("SolidWorks is not opened")
    Exit Sub
End If

Explanation:
This line connects the macro to your running SolidWorks instance. If SolidWorks is not open, it alerts the user and exits safely.

๐Ÿ”น Step 4: Get the Active Part Document

Set swDoc = swApp.ActiveDoc

If swDoc Is Nothing Then
    MsgBox ("SolidWorks document is not opened. Please open a document.")
    Exit Sub
End If 

Explanation:
The macro checks if a file is currently open in SolidWorks.

It must be a part document (.SLDPRT) where the sketch is present. If not, it alerts and exits.

๐Ÿ”น Step 5: Select the Target Sketch (e.g., “Sketch2”)

BoolStatus = swDoc.Extension.SelectByID2("Sketch2", "SKETCH", 0, 0, 0, False, 0, Nothing, swSelectOption_e.swSelectOptionDefault)

If BoolStatus = False Then
    MsgBox ("Failed to select Sketch2.")
    Exit Sub
End If

Explanation:
This selects a sketch named “Sketch2” in the model tree. You must make sure it exists. If the sketch is missing or misnamed, this block will fail gracefully.

๐Ÿ”น Step 6: Create the Cut-Extrude Feature

Set swFeature = swDoc.FeatureManager.FeatureCut4( _
    True, False, False, _
    swEndCondThroughAll, 0, _
    0.01, 0.01, _
    False, False, False, False, _
    1, 1, False, False, _
    False, False, False, _
    True, True, True, True, _
    False, swStartSketchPlane, 0, _
    False, False)

Explanation:
This performs the actual Cut-Extrude. The sketch is cut through all the geometry in the direction specified. It doesnโ€™t need to specify end depth because swEndCondThroughAll handles that.

๐Ÿ“Œ You can tweak parameters like:

0.01 = draft angles (not used if through all)

swStartSketchPlane = where to start the cut

True/False values = optional flags for merging, directions, etc.

๐Ÿ”น Step 7: Check if Feature Was Created Successfully

If swFeature Is Nothing Then
    MsgBox ("Failed to create Extrude Cut Feature.")
    Exit Sub
End If

Explanation:
Just a final check to ensure everything ran successfully. If the feature wasn’t created, the macro informs you instead of silently failing.


Frequently Asked Questions (FAQs)

โœ… What is a Cut-Extrude in SolidWorks?

A Cut-Extrude removes material from a 3D model using a 2D sketch. It’s used for holes, slots, cutouts, and other internal features.


โœ… Can I automate Cut-Extrude using a macro?

Yes, you can automate it using VBA macros in SolidWorks. The macro selects a sketch and performs a cut automaticallyโ€”saving you time on repetitive tasks.


โœ… What sketch name should the macro use?

The macro looks for a sketch named Sketch2. You can update the macro to use any valid sketch name that exists in your model.


โœ… What if the sketch isnโ€™t found?

The macro will show a message: โ€œFailed to select Sketch2.โ€ It will safely exit without making changes to your model.


โœ… Can I use this macro in assembly or drawing files?

No. This macro works only with part files (.SLDPRT). For assemblies or drawings, you need different macros.


โœ… How do I run this macro?

  1. Open SolidWorks

  2. Open your part document

  3. Press Alt + F11 to launch the VBA editor

  4. Paste the macro

  5. Run main()


โœ… What does swEndCondThroughAll mean?

Itโ€™s an end condition that tells SolidWorks to cut through all geometry in one directionโ€”ignoring cut depth values.


โœ… How can I change the cut depth instead?

Replace swEndCondThroughAll with swEndCondBlind and set your desired depth value (e.g., 0.01).


โœ… How can I check if the cut worked?

The macro checks if the feature was created. If it fails, youโ€™ll get a message: โ€œFailed to create Extrude Cut Feature.โ€


โœ… Can I extend the macro to create sketches too?

Yes! You can add API calls to draw circles, rectangles, or any sketch entity before the cut operation.


โœ… Is this macro safe to test?

Yes, but always test on a duplicate file or test part, and save your document before running any macro.


โœ… How can I perform the cut in both directions?

You can modify the macro using swEndCondMidPlane or enable two-direction cut flags in the parameters.


โœ… Where can I learn more about the SolidWorks API?

Refer to the official SolidWorks API Help Guide or visit the SolidWorks API Forums.


โœ… Can I run this on SolidWorks Student Edition?

Yes, as long as macro functionality is enabled. Some institutions may restrict macro use for security.


โœ… Can this macro be converted into a toolbar button?

Absolutely. You can embed this VBA macro into a button or convert it into a more advanced Add-In using VSTA or .NET.


๐ŸŒ Internal Reference


๐ŸŒ External References

1. ๐Ÿ”ง SolidWorks API Documentation


2. ๐Ÿ’ฌ SolidWorks API Forum (Community Help)


3. ๐ŸŽ“ MySolidWorks โ€“ Tutorials & Training

  • URL: https://my.solidworks.com/

  • Why use it? Contains beginner to advanced tutorials, including macro-related guides and how-to videos.


5. ๐Ÿ” Microsoft VBA Reference for Office Automation

Avatar of Ramu Gopal
About Author
Ramu Gopal

Ramu Gopal is the founder of The Tech Thinker and a seasoned Mechanical Design Engineer with over 10 years of industry experience in engineering design, CAD automation, and workflow optimization. He specializes in SolidWorks automation, engineering productivity tools, and AI-driven solutions that help engineers reduce repetitive tasks and improve design efficiency.

He holds a Post Graduate Program (PGP) in Artificial Intelligence and Machine Learning and combines expertise in engineering automation, artificial intelligence, and digital technologies to create practical, real-world solutions for modern engineering challenges.

Ramu is also a Certified WordPress Developer and Google-certified Digital Marketer with advanced knowledge in web hosting, SEO, analytics, and automation. Through The Tech Thinker, he shares insights on CAD automation, engineering tools, AI/ML applications, and digital technology โ€” helping engineers, students, and professionals build smarter workflows and grow their technical skills.

View All Articles

Leave a Reply

Related Posts

Table of Contents