Hello,
I have created a sketch ("Sketch1") and via extruded it via 'Extruded Boss' (to "Boss") to 2mm.
Now I want to change the depth of this extrusion in Visual Basic.
I already have the following code:
<p>Dim baseDisk, metalDisk As SldWorks.PartDoc</p><p>metalDisk = openPart("MetalDisk.sldprt")</p>How can i change the depth of the feature?
Thank you very much!
SolidworksApi macros
Hi Anne,
You need to access the IFeature interface of the extrude feature and then use IFeature::GetDefinition to access the IExtrudeFeatureData2 interface, which allows access to the properties of an extrude feature. In particular you want IExtrudeFeatureData2::SetDepth. Once you have changed the dept you need to use IFeature::ModifyDefinition to save the changes to the feature.
Try this. Create a new part and make one boss extrude feature with a depth of 50mm. Then run this macro. It should be changed to 100mm. The feature name must be "Boss-Extrude1".
---------------------
Dim swApp As SldWorks.SldWorks
Dim swModel As SldWorks.ModelDoc2
Dim swPart As SldWorks.PartDoc
Dim swFeat As SldWorks.Feature
Dim swExtrudeFeatData As SldWorks.ExtrudeFeatureData2
Sub main()
Set swApp = Application.SldWorks
Set swModel = swApp.ActiveDoc
Set swPart = swModel
Set swFeat = swPart.FeatureByName("Boss-Extrude1")
Set swExtrudeFeatData = swFeat.GetDefinition
swExtrudeFeatData.SetDepth True, 0.1
swFeat.ModifyDefinition swExtrudeFeatData, swModel, Nothing
End Sub
---------------------
Keith
Video Tutorials for the SolidWorks API
SW help shows how to do this.
http://help.solidworks.com/2012/English/api/sldworksapi/Access_Selections_Example_VB.htm
Thanks!
Just some clarifying comments...
Technically, you don't need to use AccessSelections to change the depth parameter. AccessSelections, which puts the part in a rollback state at that feature, is only necessary when you need to access the entities used to create the feature. To work with any other feature parameters it is sufficient to use IFeature::GetDefinition and IFeature::ModifyDefinition. Notice that my code above successfully modifies the feature definition but does not use AccessSelections.
Also, note that if you use AccessSelections and do NOT make any changes (and therefore do not use IFeature::ModifyDefinition) then you still need to use ReleaseSelections to remove the part from its rollback state.
Keith
CADSharp LLC
Keith,
I typically use the IDimension::SetUserValueIn2 method to change dimension values like changing extrusion depth. What are the advantages of doing it your way?
Oh .. that is SW help .. not sure why they recommend to change feature depth that way.
Yes I vaguely remember there are few other things also on feature data which can be changed without accessing selections.
Hey Wayne,
How are you accessing IDimension?
If you already have easy access to IDimension and all you need to do are change the depth, then IDimension::SetUserValueIn2 would be fastest. Otherwise, using IFeature would definitely be preferable since it is quicker to access (IMO) and gives you full control over the feature.
And actually, if you are going control the parameter via dimensions and not via the feature itself, you might as well just use IModelDoc2::Parameter. That might be even faster than IDimension::SetUserValueIn2.
Keith
CADSharp LLC
Thank you all very much for your quick response!
Unfortunately it doesn't work yet. I get the following error:
for the ModifityDefinition method...
Do you know how I can solve this exception?
This is the code:
Anne,
You have declared swFeat and swExtrudeFeatData twice. Aren't you getting an error for duplicate variable declaration?
Also, since you're using IFeature::ModifyDefinition you do not need to use IExtrudeFeatureData2::ReleaseSelectionAccess, so remove that last line.
See if this makes any difference. If not, can you post your entire module or class and state again what line is failing? Thanks.
Keith
CADSharp LLC
No, that didn't help
This is the full source-code:
Problem is at this line:
swFeat.ModifyDefinition(swExtrudeFeatData, swModel, Nothing)
CODE:
Public Class MainForm
' global variables
Dim swApp As SldWorks.SldWorks ' connection to the SolidWorks API
Dim configNames As String() ' array with configuration names
Private Sub ExitButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExitButton.Click
Close()
End Sub
Private Sub GenerateButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles GenerateButton.Click
Dim configName As String ' name of the configuration
Dim noDiskPairs As Integer ' number of disk pairs in the assembly
' connect to SolidWorks
swApp = New SldWorks.SldWorks()
If (swApp Is Nothing) Then
MsgBox("Cannot connect to SolidWorks", MsgBoxStyle.Exclamation)
Exit Sub
End If
' find the number of disk-pairs
If (Integer.TryParse(PairsTextBox.Text, noDiskPairs) = False) Then
MsgBox("Invalid number of pairs", MsgBoxStyle.Exclamation)
Exit Sub
Else
If (noDiskPairs < 1) Or (noDiskPairs > 12) Then
MsgBox(PairsTextBox.Text & " outside valid range [1..12]", _
MsgBoxStyle.Exclamation)
noDiskPairs = 0
Exit Sub
End If
End If
' get the name of the configuration
configName = CluchTypeComboBox.SelectedItem()
' create a new assembly
Dim swAssembly As SldWorks.AssemblyDoc
swAssembly = newAssembly()
If (swAssembly Is Nothing) Then
MsgBox("Failed to create new assembly", MsgBoxStyle.Exclamation)
Exit Sub
End If
' load the three parts
Dim baseDisk, metalDisk, fibreDisk As SldWorks.PartDoc
baseDisk = openPart("BaseDisk.sldprt")
metalDisk = openPart("MetalDisk.sldprt")
fibreDisk = openPart("FibreDisk.sldprt")
If (baseDisk Is Nothing) Or (metalDisk Is Nothing) Or (fibreDisk Is Nothing) Then
MsgBox("Failed to open part BaseDisk, MetalDisk or FibreDisk", _
MsgBoxStyle.Exclamation)
Exit Sub
End If
' put it together
buildAssembly(configName, noDiskPairs, swAssembly, baseDisk, metalDisk, fibreDisk)
End Sub
Private Sub MainForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
' create the list of clutch configurations
configNames = {"Standard", "High", "Racing"}
' enter the names in the typelist ComboBox
CluchTypeComboBox.Items.AddRange(configNames)
' watch the index, first one is 0
CluchTypeComboBox.SelectedIndex = 0
' deafult no disk pairs
PairsTextBox.Text = "4"
End Sub
Private Function getModelSimpleName(ByRef swDoc As SldWorks.ModelDoc2) As String
' This function dissambles the name of the assembly from its full path name
' You'll use AssemblyName when mating the component with the assembly
' an array with the separated strings
Dim strArray As String()
' get title of document
Dim documentTitle As String = swDoc.GetTitle()
' split the title into two strings using the period (.) as the delimiter
strArray = Split(documentTitle, ".")
' return first name part
Return strArray(0)
End Function
Function flipZdirection() As SldWorks.MathTransform
' This method returns a transformation matrix that flips the Z-axis by a Y-axis rotation
Dim swXform As SldWorks.MathTransform
Dim rotCenter As SldWorks.MathPoint
Dim rotAxis As SldWorks.MathVector
Dim angle As Double
rotCenter = swApp.IGetMathUtility.CreatePoint({0.0#, 0.0#, 0.0#})
rotAxis = swApp.IGetMathUtility.CreateVector({0.0#, 1.0#, 0.0#})
angle = Math.PI
swXform = swApp.IGetMathUtility.CreateTransformRotateAxis(rotCenter, rotAxis, angle) ' create unit transform
Return swXform
End Function
Private Function newAssembly() As SldWorks.AssemblyDoc
Dim assyTemplate As String
Dim swAssy As SldWorks.AssemblyDoc
' get template name
' bedenk het maar! dit kost wat clicks door de API help
assyTemplate = swApp.GetUserPreferenceStringValue( _
SwConst.swUserPreferenceStringValue_e.swDefaultTemplateAssembly)
If (assyTemplate = "") Then
MsgBox("Please define a Default Assembly Template " _
& "before running this program", _
MsgBoxStyle.Exclamation)
Return Nothing
End If
' value = instance.INewDocument2(TemplateName, PaperSize, Width, Height)
swAssy = swApp.INewDocument2(assyTemplate, 0, 0.0#, 0.0#)
Return swAssy
End Function
Private Function openPart(ByVal partName As String) As SldWorks.PartDoc
Dim errors, warnings As Integer
Dim swPart As SldWorks.PartDoc
' get pathname to parts
Dim path As String
path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) _
& "\SWparts"
If (Not System.IO.Directory.Exists(path)) Then
MsgBox("Please put the part templates in " & vbCrLf & _
path & vbCrLf & "before running this program", _
MsgBoxStyle.Exclamation)
Return Nothing
End If
swPart = swApp.OpenDoc6(path & "\" & partName, _
SwConst.swDocumentTypes_e.swDocPART, _
SwConst.swOpenDocOptions_e.swOpenDocOptions_LoadModel, _
"", _
errors, _
warnings)
Return swPart
End Function
Private Sub buildAssembly(ByVal configName As String,
ByVal noDiskPairs As Integer,
ByVal swAssembly As SldWorks.AssemblyDoc,
ByVal baseDisk As SldWorks.PartDoc,
ByVal metalDisk As SldWorks.PartDoc,
ByVal fibreDisk As SldWorks.PartDoc)
Dim diskMetalkHeight = 100
Dim diskFibreHeight = 100
If (configName = "Standaard") Then
diskMetalkHeight = 1.0
diskFibreHeight = 2.0
ElseIf (configName = "High") Then
diskMetalkHeight = 1.2
diskFibreHeight = 2.4
ElseIf (configName = "Racing") Then
diskMetalkHeight = 1.6
diskFibreHeight = 3.0
End If
diskMetalkHeight = diskMetalkHeight * 10
diskFibreHeight = diskFibreHeight * 10
' change dimensions
Dim swModel As SldWorks.ModelDoc2
swModel = swApp.ActiveDoc
Dim swFeat As SldWorks.Feature
Dim swExtrudeFeatData As SldWorks.ExtrudeFeatureData2
' Get height dimension metalpart and change
swFeat = metalDisk.FeatureByName("Base-Extrude")
swExtrudeFeatData = swFeat.GetDefinition
swExtrudeFeatData.SetDepth(True, diskMetalkHeight)
swFeat.ModifyDefinition(swExtrudeFeatData, swModel, Nothing)
' Get height dimension fibrepart and change
swFeat = fibreDisk.FeatureByName("Base")
swExtrudeFeatData = swFeat.GetDefinition
swExtrudeFeatData.SetDepth(True, diskMetalkHeight)
swFeat.ModifyDefinition(swExtrudeFeatData, swModel, Nothing)
Dim errorState As Integer
Dim component1, component2 As SldWorks.Component2
swApp.ActivateDoc2(swAssembly.GetTitle(), False, errorState)
' add parts, first base + metal
component1 = swAssembly.AddComponent5(baseDisk.GetPathName(), 0, "", False,
"Default", 0.0#, 0.0#, 0.0#)
component2 = swAssembly.AddComponent5(metalDisk.GetPathName(), 0, "", False,
"Default", 0.0#, 0.0#, 0.0#)
component2.ReferencedConfiguration = configName
' flip the base part in z-direction to prevent mate problems
component1.Transform2 = flipZdirection()
mateDisksByID(swAssembly, component1, component2)
' add pairs, fibre + metal
For index = 1 To noDiskPairs
' mate previous metal to new fibre
component1 = component2
component2 = swAssembly.AddComponent5(fibreDisk.GetPathName(), 0, "", False,
"Default", 0.0#, 0.0#, 0.0#)
component2.ReferencedConfiguration = configName
mateDisksByID(swAssembly, component1, component2)
' mate new fibre to new metal
component1 = component2
component2 = swAssembly.AddComponent5(metalDisk.GetPathName(), 0, "", False,
"Default", 0.0#, 0.0#, 0.0#)
component2.ReferencedConfiguration = configName
mateDisksByID(swAssembly, component1, component2)
Next
' rebuild etc.
swAssembly.ClearSelection2(True)
swAssembly.EnableAssemblyRebuild = True
swAssembly.ForceRebuild2(True)
End Sub
Private Sub mateDisksByID(ByVal swAssembly As SldWorks.AssemblyDoc, ByVal component1 As SldWorks.Component2, ByVal component2 As SldWorks.Component2)
Dim boolStatus As Boolean
Dim errorState As Integer
' get reference to assembly's extended function set
Dim swExt As SldWorks.ModelDocExtension
swExt = swApp.ActiveDoc().Extension
Dim assyName, compName1, compName2 As String
assyName = getModelSimpleName(swAssembly)
compName1 = component1.Name2
compName2 = component2.Name2
' add coincident mate on axes of rotation
boolStatus = swExt.SelectByID2("Axis1@" & compName1 & "@" & assyName, "AXIS",
0, 0, 0, False, 1, Nothing,
SwConst.swSelectOption_e.swSelectOptionDefault)
boolStatus = swExt.SelectByID2("Axis1@" & compName2 & "@" & assyName, "AXIS",
0.0#, 0.0#, 0.0#, True, 1, Nothing,
SwConst.swSelectOption_e.swSelectOptionDefault)
swAssembly.AddMate3(SwConst.swMateType_e.swMateCOINCIDENT,
SwConst.swMateAlign_e.swMateAlignALIGNED,
False, 0.0#, 0.0#, 0.0#, 1.0#, 1.0#, 0.0#, 0.0#, 0.0#,
False, errorState)
' add coincident mate of front- and back surface
boolStatus = swExt.SelectByID2("RefPlane2@" & compName1 & "@" & assyName, "PLANE",
0, 0, 0, False, 1, Nothing,
SwConst.swSelectOption_e.swSelectOptionDefault)
boolStatus = swExt.SelectByID2("RefPlane1@" & compName2 & "@" & assyName, "PLANE",
0.0#, 0.0#, 0.0#, True, 1, Nothing,
SwConst.swSelectOption_e.swSelectOptionDefault)
swAssembly.AddMate3(SwConst.swMateType_e.swMateCOINCIDENT,
SwConst.swMateAlign_e.swAlignAGAINST,
False, 0.0#, 0.0#, 0.0#, 1.0#, 1.0#, 0.0#, 0.0#, 0.0#,
False, errorState)
End Sub
Private Sub Moment(ByVal swAssembly As SldWorks.AssemblyDoc)
End Sub
Private Sub Diepte(ByVal swAssembly As SldWorks.AssemblyDoc)
End Sub
Private Sub Volume(ByVal swAssembly As SldWorks.AssemblyDoc)
End Sub
Private Sub Gewicht(ByVal swAssembly As SldWorks.AssemblyDoc)
Dim gewicht = swAssembly.GetLightWeightComponentCount
LabelGewicht.Text = gewicht
End Sub
End Class
Thank you!
Anne,
Can you verify that a part is the active document when that problematic code is being run? Because if you are in an assembly then the third argument of IFeature::GetDefinition needs to be the component. (See the documentation for more remarks.)
Have you tested the feature modification code in its own separate macro? You should make sure it is working outside of your current project before you include it.
Keith
CADSharp LLC
When I try the code u gave me earlier, it works in a macro for one part.
This code compiles without errors, and it works!
For those with similar problems: When I opened multiple parts the activeDoc was wrong, so when you
want to change something from part x.sldpt, you must run
<p>swModel = swApp.ActivateDoc2("x", True, errors)</p>first to set part x as the active part.
The complete solution:
<p> ' change dimensions</p><p> Dim swModel As SldWorks.ModelDoc2</p><p> swModel = swApp.ActiveDoc</p><p> Dim swFeat As SldWorks.Feature</p><p> Dim swExtrudeFeatData As SldWorks.ExtrudeFeatureData2</p><p> Dim errors As Long</p><p></p><p></p><p> ' Get height dimension metalpart and change</p><p> swModel = swApp.ActivateDoc2("MetalDisk", True, errors)</p><p> metalDisk = swModel</p><p> swFeat = metalDisk.FeatureByName("Base-Extrude")</p><p> swExtrudeFeatData = swFeat.GetDefinition</p><p> swExtrudeFeatData.SetDepth(True, diskMetalkHeight)</p><p> swFeat.ModifyDefinition(swExtrudeFeatData, swModel, Nothing)</p><p></p><p></p><p> ' Get height dimension fibrepart and change</p><p> swModel = swApp.ActivateDoc2("FibreDisk", True, errors)</p><p> fibreDisk = swModel</p><p> swFeat = fibreDisk.FeatureByName("Base")</p><p> swExtrudeFeatData = swFeat.GetDefinition</p><p> swExtrudeFeatData.SetDepth(True, diskFibreHeight)</p><p> swFeat.ModifyDefinition(swExtrudeFeatData, swModel, Nothing)</p>Thank you very much for your help!
Hi Anne,
That is good to hear. If your original question was answered then please mark the thread as 'answered'.
Thanks,
CADSharp LLC