PDA

View Full Version : [SOLVED] need help with regex



elmnas
05-26-2015, 01:07 AM
Hello guys I found this code on the forum

Could someone help me to add a regex expression


instead of
"change me" and "Changed!"
I want to search for "><"

and replace with ">\n\r<"

see code below


Sub CleanupXML()
Dim FSO As Object '//FileSystemObject
Dim ts(1) As Object '//TextStream
Dim s As String, t As String
Dim FileContents As String

'---------------------------------------------------------
Const SEARCH_FOR As String = "Change me" 'Search for ><
Const REPLACE_WITH As String = "Changed!" 'replace with >\n\r<
'---------------------------------------------------------

On Error GoTo ErrHandler:
s = Application.GetOpenFilename()
If s <> "False" Then
Set FSO = CreateObject("Scripting.FileSystemObject")
If FSO.FileExists(s) Then

'//Get File Contents
t = FSO.GetParentFolderName(s) & "\" & Replace(FSO.GetTempName(), ".tmp", ".xml")
Name s As t
Set ts(0) = FSO.OpenTextFile(t, 1, False, -2) '//For reading, use default encoding
FileContents = ts(0).ReadAll
ts(0).Close
Set ts(0) = Nothing

'//Make replacement
FileContents = Replace(FileContents, SEARCH_FOR, REPLACE_WITH)

'//Write new file contents
Set ts(1) = FSO.OpenTextFile(s, 2, True, -2) '//For writing, use default encoding
ts(1).Write (FileContents)
ts(1).Close
Set ts(1) = Nothing

'//Delete Temp file if all actions succeeded
FSO.DeleteFile (t)

End If
End If

'//Check that all files are closed
My_Exit:
If Not ts(0) Is Nothing Then
ts(0).Close
End If
If Not ts(1) Is Nothing Then
ts(1).Close
End If
Set FSO = Nothing
Exit Sub

ErrHandler:
MsgBox "Error " & Err.Number & ": " & Err.Description
Resume My_Exit
End Sub


Thank you in advance

snb
05-26-2015, 02:54 AM
This will suffice:


Sub M_snb()
Set fc = CreateObject("scripting.filesystemobject")

With Application.FileDialog(1)
If .Show <> False Then fc.opentextfile(.SelectedItems(1), ForWriting).write Replace(fc.opentextfile(.SelectedItems(1)).readall, "><", ">\\n\\r<")
End With
End Sub


NB please use codetags around VBA-code

elmnas
05-26-2015, 04:15 AM
I get this error:

Run-time error '5';

Invalid producedure call or argument.

snb
05-26-2015, 04:21 AM
Where, which line? Please be specific in your feedback !

Which file did you select ?

mancubus
05-26-2015, 04:29 AM
@snb

'2' instead of 'ForWriting'?

elmnas
05-26-2015, 04:41 AM
I did select an xml file

13515