Hi. I am receiving an XML file that needs to be 'tweeked' before I can properly import it into to my Access database. I need to replace the first and fourth instance of'cb:TRINGLE'. I am able to replace the first instance of ‘cb:TRINGLE’ in the xml file. My problem now is that I do not want all instances to be replaced. I only want the first and fourth … In the following code you can see that I am able to locate the position of the fourth instance (I think) but I end up with the entire begining of the file missing!
Is there a better way to only replace certain matches with the Replace function?
Can someone please help me with this?!
Is there a better way to only replace certain matches with the Replace function?
Code:
Function FindAndReplaceXMLText() Dim sSearchText As String Dim sReplaceText As String Dim sFileName As String Dim sFileText As String Dim strText As String Dim strNewText As String Dim intWhere1 As Integer Dim FirstPos, NextPos Const ForReading = 1 Const ForWriting = 2 sSearchText = “cb:TRINGLE” sReplaceText = “cb:MATERIAL” sFileName = “C:XMLtestexport.xml” ‘Create instance of FileSystemObject. Set objFSO = CreateObject(”Scripting.FileSystemObject”) Set objFile = objFSO.OpenTextFile(sFileName, ForReading) ‘read entire contents of file, save to strText variable strText = objFile.ReadAll objFile.Close ‘Search for text in string. strNewText = Replace(strText, sSearchText, sReplaceText, , 1, vbTextCompare) Set objFile = objFSO.OpenTextFile(sFileName, ForWriting) objFile.WriteLine strNewText objFile.Close ‘Create instance of FileSystemObject. Set objFSO = CreateObject(”Scripting.FileSystemObject”) Set objFile = objFSO.OpenTextFile(sFileName, ForReading) ‘read entire contents of file, save to strText variable strText = objFile.ReadAll objFile.Close FirstPos = InStr(1, strText, sSearchText, 1) NextPos = FirstPos + 10 FirstPos = InStr(NextPos, strText, sSearchText, 1) NextPos = FirstPos + 10 strNewText = Replace(strText, sSearchText, sReplaceText, NextPos, 1, vbTextCompare) Set objFile = objFSO.OpenTextFile(sFileName, ForWriting) objFile.WriteLine strNewText objFile.Close End Function
Comment