' 给现有部件注入参数化表达式 (真数模做母模的管线验证用; 不改几何, 只加 bore/stroke/magOn/mountIdx)
Option Strict Off
Imports System
Imports System.IO
Imports System.Text
Imports NXOpen
Imports NXOpen.UF

Module AddExpressions
    Sub Main()
        Dim lw As ListingWindow = Session.GetSession().ListingWindow
        lw.Open()
        Dim outPath As String = Path.Combine(Directory.GetCurrentDirectory(), "KC_master.prt")
        If Not File.Exists(outPath) Then
            lw.WriteLine("部件缺失: " & outPath)
            Return
        End If
        Dim partLoadStatus1 As NXOpen.PartLoadStatus = Nothing
        Session.GetSession().Parts.OpenBaseDisplay(outPath, partLoadStatus1)
        Dim w As Part = Session.GetSession().Parts.Work
        If w Is Nothing Then
            lw.WriteLine("打开失败")
            Return
        End If
        Dim mm As NXOpen.Unit = w.UnitCollection.FindObject("MilliMeter")
        Try
            If mm IsNot Nothing Then
                w.Expressions.CreateExpressionWithUnit("Number", "bore=32", mm)
                w.Expressions.CreateExpressionWithUnit("Number", "stroke=10", mm)
            Else
                w.Expressions.CreateExpression("Number", "bore=32")
                w.Expressions.CreateExpression("Number", "stroke=10")
            End If
            w.Expressions.CreateExpression("Number", "magOn=0")
            w.Expressions.CreateExpression("Number", "mountIdx=0")
            lw.WriteLine("表达式已注入")
        Catch ex As Exception
            lw.WriteLine("表达式注入失败: " & ex.Message)
            Return
        End Try
        Dim pss As NXOpen.PartSaveStatus = w.Save(NXOpen.BasePart.SaveComponents.True, NXOpen.BasePart.CloseAfterSave.False)
        If pss IsNot Nothing Then pss.Dispose()
        lw.WriteLine("已保存: " & outPath)
    End Sub
End Module
