3 Replies Latest reply on Jul 28, 2015 1:46 AM by Rajat Jain

    How to extract part of a file name VBA?

    Matt Jones

      How do I extract part of the path VBA code?

      eg. The path is

      C:\Users\m.jones\Desktop\New folder (2)\LS4102-104-01 Fixed Table.slddrw

      All I want from this is the "Fixed Table" part.

        • Re: How to extract part of a file name VBA?
          Matt Jones

          I just experimented and stumbled upon something that worked.. Am I going to run in to issues with the following or is it solid?

           

               PartNoDes = Mid(swDraw.GetPathName, InStrRev(swDraw.GetPathName, "\") + 1)

               PartNoDes = Right(PartNoDes, Len(PartNoDes) - 14)

               PartNoDes = Left(PartNoDes, Len(PartNoDes) - 7)

            • Re: How to extract part of a file name VBA?
              Deepak Gupta

              This should be fine if your files name always has same number of characters.

              • Re: How to extract part of a file name VBA?
                Rajat Jain

                Matt,

                 

                Actually you should use the following code: -

                 

                Option Explicit

                Dim swApp As SldWorks.SldWorks

                Dim swModel As SldWorks.ModelDoc2

                Sub main()

                    Set swApp = Application.SldWorks

                    Set swModel = swApp.ActiveDoc

                    Dim str As String

                    str = swModel.GetPathName

                    Dim strExtension As String

                   

                    Dim oFso As New Scripting.FileSystemObject

                    strExtension = oFso.GetExtensionName(str) ' Get extension from file name

                    str = oFso.GetFileName(str) ' Get file name without path but with extension

                    Set oFso = Nothing

                    str = Left(str, Len(str) - Len(strExtension) - 1) ' Remove Extension from file name

                   

                    Dim oObj As Variant

                    oObj = Split(str, " ")

                    If UBound(oObj) > 0 Then

                        str = Right(str, Len(str) - Len(oObj(LBound(oObj)))) ' Remove the first block of string before a space

                    End If

                    MsgBox (str)

                End Sub

                 

                You need to add a reference to "Microsoft Scripting Runtime" library to use the scripting class here. To do this, goto Tools->References and check "Microsoft Scripting Runtime" as shown below: -

                 

                Hope it helps!!!

                 

                Rajat Jain