arraysvbareplacesavesolidworks

Temporarily replace values in string


I have a very simple question for you, but I cannot find it on the internet. I have a list called ArrayList(i) of which I want to replace some strings for only one line. After that line, it should be changed back again. It works, but I want to learn how to do this more efficiently. I presume I need a loop only for the "fileName" line, but I'm not sure. The length of ArrayList is different everytime, and does not always contain the strings to be replaced, only somtimes.

    'REPLACE NAME
    ArrayList(i) = Replace(ArrayList(i), "NameOld1", "NameNew1")
    ArrayList(i) = Replace(ArrayList(i), "NameOld2", "NameNew2")
    
    finalName = PathCut & "XT\" & NumPart(initName) & "_" & partcode & " " & ArrayList(i) & " " & CodeNR & ExtNew

    'REPLACE NAME BACK
    ArrayList(i) = Replace(ArrayList(i), "NameNew1", "NameOld1")
    ArrayList(i) = Replace(ArrayList(i), "NameNew2", "NameOld2")

    swApp.CloseDoc ArrayList(i) & ".SLDPRT" 'Close the files

I am sure there must be an easier and cleaner way. Thank you in advance!


Solution

  • Introduce a new variable newStr and use nested Replace function, then you don't have to revert it with last two replacement.

        Dim newStr As String
        newStr = Replace(Replace(ArrayList(i), "NameOld1", "NameNew1"), "NameOld2", "NameNew2")
        
        finalName = PathCut & "XT\" & NumPart(initName) & "_" & partcode & " " & newStr & " " & CodeNR & ExtNew
    
        swApp.CloseDoc ArrayList(i) & ".SLDPRT" 'Close the files