1

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!

2
  • 4
    How about using a temporary string and not replacing in the array itself? This sting you could use the creation of the filename. Commented Aug 26, 2024 at 10:07
  • 2
    What is NumPart? When you say having a list, do you mean an array? If not sure, how does your code load it? If an array, you can replace at once, using the joined array. Something like Dim strArr as String strArr=join(ArrayList, "|") then ArrayList = split(Replace(Replace(strArr, "NameOld1", "NameNew1"), "NameOld2", "NameNew2"), "|"). Now you have the array with replaced strings. You can use a different array for that (arrRepl = ...). If the string to be replaced does not exist, nothing wrong happens. Commented Aug 26, 2024 at 10:51

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.