5 Replies Latest reply on Dec 29, 2016 8:56 AM by Gabriel Bueno

    Change a global variable using a macro?

    Alex Brewer

      Hello,

       

      I'd like to change a global variable using a vb macro. How do I accomplish this?

       

      Here's my attempt that does nothing:

       


      Dim swApp As SldWorks.SldWorks
      Dim swModel As SldWorks.ModelDoc2
      Dim swEqnMgr As SldWorks.EquationMgr


      Sub main(dim_name As String, dim_val As Long)

          Set swApp = Application.SldWorks
          Set swModel = swApp.ActiveDoc
          Set swEqnMgr = swModel.GetEquationMgr
         
          Dim eqn As String
          Dim val As Double
         
          i = swEqnMgr.GetCount
         
          While i > 0
              eqn = swEqnMgr.Equation(i)
              a = InStr(eqn, "@")
             
                  If (a = 0) And eqn = dim_name Then
                 
                       swEqnMgr.Value(i) = dim_val
                     
                  End If
                 
              i = i - 1
             
          Wend
         
          swModel.ForceRebuild3 False
         
      End Sub

        • Re: Change a global variable using a macro?
          Keith Rice

          Alex,

           

          IEquationMgr::Value is get-only. You cannot use it to set a value. You need to use IEquationMgr::Equation to change the value. There's many different ways you could write code that does this, but here's one way:

           

          Const VARIABLE_NAME As String = "var1"

          Const NEW_VALUE As String = "2"

           

          Dim swApp As SldWorks.SldWorks

          Dim swModel As SldWorks.ModelDoc2

          Dim swEqnMgr As SldWorks.EquationMgr

          Dim i As Integer

          Dim vSplit As Variant

           

          Sub main()

              Set swApp = Application.SldWorks

              Set swModel = swApp.ActiveDoc

              Set swEqnMgr = swModel.GetEquationMgr

           

              For i = 0 To swEqnMgr.GetCount - 1

                  vSplit = Split(swEqnMgr.Equation(i), " = ")

                  vSplit(0) = Replace(vSplit(0), Chr(34), Empty)

                  If vSplit(0) = VARIABLE_NAME Then _

                      swEqnMgr.Equation(i) = Replace(swEqnMgr.Equation(i), vSplit(1), NEW_VALUE)

              Next i

          End Sub

           

          Hope this helps. By the way, did you know that you can run VBA code in equations? Check this out --- it's pretty cool.

           

          Keith

          SolidWorks API Video Tutorials