Solidworks VBA Macro - Create Reference Plane

15 minute read

This article 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 Reference Plane in SOLIDWORKS CAD Software.

This method is most updated method, so use this method if you want to create a new Reference Plane quickly.

Results We Can Get

After running our macro we successfully create Reference Plane as a result.

Below image shows the result we get.

scale-feature-final-result

We create Reference Plane in following steps in general.

  1. Ask for Distance.

To get the correct result please follow the steps correctly.

Macro Video

Below ๐ŸŽฌ video shows Reference Plane 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 Reference Plane.

Option Explicit

' Main program for Reference Plane
Sub main()

  ' Variable for Solidworks application
  Dim swApp As SldWorks.SldWorks
  
  ' 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
  
  ' Variable for storing default part location
  Dim defaultTemplate As String
  
  ' Setting value of variable to "Default part template"
  defaultTemplate = swApp.GetUserPreferenceStringValue(swUserPreferenceStringValue_e.swDefaultTemplatePart)

  ' Variable for Solidworks document
  Dim swDoc As SldWorks.ModelDoc2
  
  ' Setting Solidworks document to new part document
  Set swDoc = swApp.NewDocument(defaultTemplate, 0, 0, 0)
  
  ' 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
  
  ' Local variables used as Conversion Factors
  Dim LengthConversionFactor As Double
  Dim AngleConversionFactor As Double
  
  ' Use a Select Case, to get the length of active Unit and set the different factors
  Select Case swDoc.GetUnits(0)       ' GetUnits function gives us, active unit
    
    Case swMETER    ' If length is in Meter
      LengthConversionFactor = 1
      AngleConversionFactor = 1
    
    Case swMM       ' If length is in MM
      LengthConversionFactor = 1 / 1000
      AngleConversionFactor = 1 * 0.01745329
    
    Case swCM       ' If length is in CM
      LengthConversionFactor = 1 / 100
      AngleConversionFactor = 1 * 0.01745329
    
    Case swINCHES   ' If length is in INCHES
      LengthConversionFactor = 1 * 0.0254
      AngleConversionFactor = 1 * 0.01745329
    
    Case swFEET     ' If length is in FEET
      LengthConversionFactor = 1 * (0.0254 * 12)
      AngleConversionFactor = 1 * 0.01745329
    
    Case swFEETINCHES     ' If length is in FEET & INCHES
      LengthConversionFactor = 1 * 0.0254  ' For length we use sama as Inch
      AngleConversionFactor = 1 * 0.01745329
    
    Case swANGSTROM        ' If length is in ANGSTROM
      LengthConversionFactor = 1 / 10000000000#
      AngleConversionFactor = 1 * 0.01745329
    
    Case swNANOMETER       ' If length is in NANOMETER
      LengthConversionFactor = 1 / 1000000000
      AngleConversionFactor = 1 * 0.01745329
    
    Case swMICRON       ' If length is in MICRON
      LengthConversionFactor = 1 / 1000000
      AngleConversionFactor = 1 * 0.01745329
  End Select
  
  ' Variable to hold user input
  Dim response As String
  
  ' Getting Distance from user.
  response = InputBox("Please Enter [Distance] from Front Plane:")
  
  ' This will handle empty value or cancel case
  If Len(response) = 0 Then
    MsgBox "Empty or no value. Please try again."
    swDoc.ClearSelection2 True
    Exit Sub
  End If
  
  ' This will handle case for Non-numeric values
  If IsNumeric(response) = False Then
    MsgBox "Entered value is Non-numeric. Please try again."
    swDoc.ClearSelection2 True
    Exit Sub
  End If
  
  ' Variable for Distance
  Dim distance As Double
  
  ' Set Distance
  distance = CDbl(response) * LengthConversionFactor
  
  ' This will handle case for 0 Distance
  If distance = 0 Then
    MsgBox "Entered value must be greater than 0. Please try again."
    swDoc.ClearSelection2 True
    Exit Sub
  End If
  
  ' Boolean Variable
  Dim BoolStatus As Boolean
  
  ' Selecting Front Plane
  BoolStatus = swDoc.Extension.SelectByID2("Front", "PLANE", 0, 0, 0, False, 0, Nothing, swSelectOption_e.swSelectOptionDefault)
  
  ' Variable for Solidworks Reference Plane
  Dim swRefPlane As SldWorks.RefPlane
  
  ' Create Reference Plane
  Set swRefPlane = swDoc.FeatureManager.InsertRefPlane(swRefPlaneReferenceConstraints_e.swRefPlaneReferenceConstraint_Distance, distance, 0, 0, 0, 0)
  
  ' Check if Reference Plane creates or not
  If swRefPlane Is Nothing Then
    MsgBox ("Failed to create Reference Plane.")
    swDoc.ClearSelection2 True
    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.

  • Knowledge of VBA programming language is โ—required.

Since we are creating new part, there are no feature to create.

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

Steps To Follow

This Reference Plane VBA macro can be divided into following sections:

  1. Create and Initialize required variables
  2. Get Distance And Validation
  3. Get Distance And Validation
  4. Create Reference Plane
  5. 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.

Create and Initialize required variables

In this section we create and initialize required variables.

Option Explicit
' Main program for Scale Feature
Sub main()

End Sub
  • In above line, we create main program for Scale 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.
' 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.

Inside this section we initialize required variables.

' Set Solidworks Application 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.
' Variable for storing default part location
Dim defaultTemplate As String
  • Purpose: In above line, we create a variable for storing default part location.
  • Variable Name: defaultTemplate
  • Type: String
' Setting value of variable to "Default part template"
defaultTemplate = swApp.GetUserPreferenceStringValue(swUserPreferenceStringValue_e.swDefaultTemplatePart)
  • In above line, we set value of defaultTemplate variable.
  • This value is set to โ€œDefault part templateโ€.
' 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.
' Set Solidworks document variable to new part document
Set swDoc = swApp.NewDocument(defaultTemplate, 0, 0, 0)
  • In above line, we set value of swDoc variable.
  • This value is new 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.

Get unit Conversion factors

In this section we get unit Conversion factors.

' Local variables used as Conversion Factors
Dim LengthConversionFactor As Double
Dim AngleConversionFactor As Double

' Use a Select Case, to get the length of active Unit and set the different factors
Select Case swDoc.GetUnits(0)       ' GetUnits function gives us, active unit

Case swMETER    ' If length is in Meter
  LengthConversionFactor = 1
  AngleConversionFactor = 1

Case swMM       ' If length is in MM
  LengthConversionFactor = 1 / 1000
  AngleConversionFactor = 1 * 0.01745329

Case swCM       ' If length is in CM
  LengthConversionFactor = 1 / 100
  AngleConversionFactor = 1 * 0.01745329

Case swINCHES   ' If length is in INCHES
  LengthConversionFactor = 1 * 0.0254
  AngleConversionFactor = 1 * 0.01745329

Case swFEET     ' If length is in FEET
  LengthConversionFactor = 1 * (0.0254 * 12)
  AngleConversionFactor = 1 * 0.01745329

Case swFEETINCHES     ' If length is in FEET & INCHES
  LengthConversionFactor = 1 * 0.0254  ' For length we use sama as Inch
  AngleConversionFactor = 1 * 0.01745329

Case swANGSTROM        ' If length is in ANGSTROM
  LengthConversionFactor = 1 / 10000000000#
  AngleConversionFactor = 1 * 0.01745329

Case swNANOMETER       ' If length is in NANOMETER
  LengthConversionFactor = 1 / 1000000000
  AngleConversionFactor = 1 * 0.01745329

Case swMICRON       ' If length is in MICRON
  LengthConversionFactor = 1 / 1000000
  AngleConversionFactor = 1 * 0.01745329
End Select

Get Distance And Validation

In this section, we get get the Distance from user and apply some validation on Distance.

' Variable to hold user input
Dim response As String
  • In above line, we create a variable hold user input.
  • Variable Name: response
  • Type: String
' Getting Distance from user
response = InputBox("Please Enter [Distance] from Front Plane:")
  • In above line of code we are doing 2 steps in one line.

    Those 2 steps are explained below.

    • Step 1 - Getting Distance from user.

    Below image shows the message for Distance to the user.

    message-to-enter-distance

    • Step 2 - Assigned input value to response variable.
' This will handle empty value or cancel case
If Len(response) = 0 Then  
  MsgBox "Empty or no value. Please try again."  
  swDoc.ClearSelection2 True
  Exit Sub
End If
  • In above code block, we check the length of input value.
  • This check will handle case for empty value or cancel operation case.

message-to-enter-distance

  • We use ๐Ÿš€ IF statement for checking.

  • Condition: Len(response) = 0
    • Len() is pre-build VBA function which check the length of a object.
    • In above cases, we will get 0 value.
  • When this condition is True,
    • We show and ๐Ÿš€ message window to user.
    • Message: Empty or no value. Please try again.

    message-to-show-when-empty-or-no-value-given

    • Then we stop our macro here.
' This will handle case for Non-numeric values
If IsNumeric(response) = False Then  
  MsgBox "Entered value is Non-numeric. Please try again."  
  swDoc.ClearSelection2 True
  Exit Sub
End If
  • In above code block, we check if the input value is Non-numeric.
  • This check will handle case for Non-numeric values.
  • We use ๐Ÿš€ IF statement for checking.
  • Condition: IsNumeric(response) = False
    • IsNumeric() is pre-build VBA function which check if passing object is Numeric or not.

    entering-non-numeric-value

    • In above cases, we will get False value.
  • When this condition is True,
    • We show and ๐Ÿš€ message window to user.
    • Message: Entered value is Non-numeric. Please try again.

    message-to-show-non-numeric-value-given

    • Then we stop our macro here.
' Variable for distance
Dim distance As Double
  • In above line, we create a variable to store Distance.
  • Variable Name: distance
  • Type: Double
' Set Distance
distance = CDbl(response)
  • In above line of code we are doing 2 steps in one line.

    Those 3 steps are explained below.

    • Step 1 - Converting Distance from user to Double type.
    • Step 2 - Assigned input value to distance variable.
' This will handle case for 0 Distance
If scaleFactor = 0 Then
  MsgBox "Entered value must be greater than 0. Please try again."
  swDoc.ClearSelection2 True
  Exit Sub
End If
  • In above code block, we check if the input value is zero (0).
  • This check will handle case for 0 Distance.
  • We use ๐Ÿš€ IF statement for checking.
  • Condition: distance = 0

entering-zera-as-value

  • When this condition is True,
    • We show and ๐Ÿš€ message window to user.
    • Message: Entered value must be greater than 0. Please try again.

    message-to-show-on-zero-given

    • Then we stop our macro here.

Create Reference Plane

In this section, we create Reference Plane.

' Boolean Variable
Dim BoolStatus As Boolean
  • Purpose: In above line, we create a variable Boolean values or function.
  • Variable Name: BoolStatus
  • Type: Boolean
' Selecting Front Plane
BoolStatus = swDoc.Extension.SelectByID2("Front", "PLANE", 0, 0, 0, False, 0, Nothing, swSelectOption_e.swSelectOptionDefault)
  • In above line, we select Front plane by SelectByID2 method.
  • If we succeed in selecting Front plane, we get True otherwise we get False.
' Variable for Solidworks Reference Plane
Dim swRefPlane As SldWorks.RefPlane
  • Purpose: In above line, we create a variable for Solidworks Reference Plane.
  • Variable Name: swRefPlane
  • Type: SldWorks.RefPlane
  • Reference: Please visit ๐Ÿš€ online SOLIDWORKS API Help.
' Create Reference Plane
Set swRefPlane = swDoc.FeatureManager.InsertRefPlane(swRefPlaneReferenceConstraints_e.swRefPlaneReferenceConstraint_Distance, distance, 0, 0, 0, 0)
  • In above line, we set the value of variable swRefPlane by InsertRefPlane method.

  • This InsertRefPlane method takes following parameters as explained:

    • FirstConstraint - First constraint as defined in swRefPlaneReferenceConstraints_e:

      Member Description
      swRefPlaneReferenceConstraint_Angle 16
      swRefPlaneReferenceConstraint_Coincident 4
      swRefPlaneReferenceConstraint_Distance 8
      swRefPlaneReferenceConstraint_MidPlane 128
      swRefPlaneReferenceConstraint_OptionFlip 256
      swRefPlaneReferenceConstraint_OptionOriginOnCurve 512
      swRefPlaneReferenceConstraint_OptionProjectAlongSketchNormal 2056
      swRefPlaneReferenceConstraint_OptionProjectToNearestLocation 1028
      swRefPlaneReferenceConstraint_OptionReferenceFlip 8192
      swRefPlaneReferenceConstraint_Parallel 1
      swRefPlaneReferenceConstraint_ParallelToScreen 4096
      swRefPlaneReferenceConstraint_Perpendicular 2
      swRefPlaneReferenceConstraint_Project 64
      swRefPlaneReferenceConstraint_Tangent 32
    • FirstConstraintAngleOrDistance - Angle or distance of the first constraint.

    • SecondConstraint - Second constraint as defined in swRefPlaneReferenceConstraints_e:

      Member Description
      swRefPlaneReferenceConstraint_Angle 16
      swRefPlaneReferenceConstraint_Coincident 4
      swRefPlaneReferenceConstraint_Distance 8
      swRefPlaneReferenceConstraint_MidPlane 128
      swRefPlaneReferenceConstraint_OptionFlip 256
      swRefPlaneReferenceConstraint_OptionOriginOnCurve 512
      swRefPlaneReferenceConstraint_OptionProjectAlongSketchNormal 2056
      swRefPlaneReferenceConstraint_OptionProjectToNearestLocation 1028
      swRefPlaneReferenceConstraint_OptionReferenceFlip 8192
      swRefPlaneReferenceConstraint_Parallel 1
      swRefPlaneReferenceConstraint_ParallelToScreen 4096
      swRefPlaneReferenceConstraint_Perpendicular 2
      swRefPlaneReferenceConstraint_Project 64
      swRefPlaneReferenceConstraint_Tangent 32
    • SecondConstraintAngleOrDistance - Angle or distance of the second constraint.

    • ThirdConstraint - Third constraint as defined in swRefPlaneReferenceConstraints_e:

      Member Description
      swRefPlaneReferenceConstraint_Angle 16
      swRefPlaneReferenceConstraint_Coincident 4
      swRefPlaneReferenceConstraint_Distance 8
      swRefPlaneReferenceConstraint_MidPlane 128
      swRefPlaneReferenceConstraint_OptionFlip 256
      swRefPlaneReferenceConstraint_OptionOriginOnCurve 512
      swRefPlaneReferenceConstraint_OptionProjectAlongSketchNormal 2056
      swRefPlaneReferenceConstraint_OptionProjectToNearestLocation 1028
      swRefPlaneReferenceConstraint_OptionReferenceFlip 8192
      swRefPlaneReferenceConstraint_Parallel 1
      swRefPlaneReferenceConstraint_ParallelToScreen 4096
      swRefPlaneReferenceConstraint_Perpendicular 2
      swRefPlaneReferenceConstraint_Project 64
      swRefPlaneReferenceConstraint_Tangent 32
    • ThirdConstraintAngleOrDistance - Angle or distance of the third constraint.

  • Return Value : This InsertRefPlane method return ๐Ÿš€ Reference Plane data object.

  • In our code, I have used following values:

    Parameter Name Value Used
    FirstConstraint swRefPlaneReferenceConstraints_e.swRefPlaneReferenceConstraint_Distance
    FirstConstraintAngleOrDistance distance
    SecondConstraint 0
    SecondConstraintAngleOrDistance 0
    ThirdConstraint 0
    ThirdConstraintAngleOrDistance 0

Reference: For more details about

' Check if Reference Plane creates or not
If swRefPlane Is Nothing Then
  MsgBox ("Failed to create Reference Plane.")
  swDoc.ClearSelection2 True
  Exit Sub
End If
  • In above code block, we check if we successfully create Reference Plane or not.
  • We use ๐Ÿš€ IF statement for checking.
  • Condition: swRefPlane Is Nothing
  • When this condition is True,
    • We show and ๐Ÿš€ message window to user.
    • Message: Failed to create Reference Plane.
    • Then we clear all selection and stop our macro here.

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

scale-feature-final-result

Final work

In this section, after creating Reference Plane, we have to do some cleaning work so that we can use this macro frequently.

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

Error-Solutions

After posting this article, I got to know that code sample is not working for already opened document.

I thought writing a section for these error will be a better idea or future.

Below I list out the error message we got and their probable solution(s).

Error Message 1

Solidworks document is opened error message. Image of this error is shown below.

error-solidworks-document-not-open

Cause: Cause of this error is not setting File Location setting for Document Templates.

Please see below image for detail.

document-template-setting

After setting Document Templates path, this message will not come.

Error Message 2

Failed to create Reference Plane error message. Image of this error is shown below.

failed-to-create-plane

Cause: There might be 2 causes for this error.

  1. Code for getting Distance from user is commented.
  2. Name of selected plane is different.

In case of reason 1, I canโ€™t do anything. Commented code did not executed

In case of reason 2, you need to confirm plane name first, as I shown in below image.

plane-names

As shown in above image, in my default part, plane name is โ€œFrontโ€.

Hence for selecting this plane, I use below code.

' Selecting Front Plane
BoolStatus = swDoc.Extension.SelectByID2("Front", "PLANE", 0, 0, 0, False, 0, Nothing, swSelectOption_e.swSelectOptionDefault)

If your default part have plane name as shown in below image.

plane-names-with-suffix-plane

Then you need to use below code for selecting Front Plane.

' Selecting Front Plane
BoolStatus = swDoc.Extension.SelectByID2("Front Plane", "PLANE", 0, 0, 0, False, 0, Nothing, swSelectOption_e.swSelectOptionDefault)

Error 3

If you are using code sample provided in this article into an already open document.

And hoping that you will get the result of new Reference Plane in opened document.

Then I suggest you to know few things:

  1. This code sample, create new part and in that new part it create reference plane.
  2. If you are in this error section, I seriously want you to read all articles I had written. Then you will understand the code and change it to fit your need.

If you still want to create new Reference plane in already opened document, do following.

' Variable for storing default part location
Dim defaultTemplate As String

' Setting value of variable to "Default part template"
defaultTemplate = swApp.GetUserPreferenceStringValue(swUserPreferenceStringValue_e.swDefaultTemplatePart)

' Variable for Solidworks document
Dim swDoc As SldWorks.ModelDoc2

' Setting Solidworks document to new part document
Set swDoc = swApp.NewDocument(defaultTemplate, 0, 0, 0)

Replace above code, with below code in your macro.

' Variable for Solidworks document
Dim swDoc As SldWorks.ModelDoc2

' Set Solidworks document variable to currently opened document
Set swDoc = swApp.ActiveDoc

I hope this will work.

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 Reference Plane 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!!!

Updated: