|
-
Aug 7th, 2001, 12:56 AM
#1
Thread Starter
Junior Member
How Do I Find and Replace....?
Hi, I'm trying to write a piece of code that will look for text thats inputted in my FindString text box in my Source text file and replace it with text in another text box and write it to my target file. How do I go about doing this. I've got this far and now I'm stuck. I know how to copy from one file to another but how do I find and replace.
Thanks
Vaastav
Private Sub cmdReplace_Click()
Dim sdata As String
Dim FindString As String
Dim ReplaceWith As String
FindString = txtFindString.Text
ReplaceWith = txtReplaceWith.Text
Open "c:\Source.txt" For Input As #1
Open "c:\Target.txt" For Output As #2
While Not EOF(1)
Line Input #1, sdata
Wend
Print #2, sdata
Close #1
Close #2
End Sub
-
Aug 7th, 2001, 01:04 AM
#2
Use the InStr function to find the text, and if you wish to replace all instances of certain text, you can use the Replace function.
InStr([start, ]string1, string2[, compare])
Replace(expression, find, replacewith[, start[, count[, compare]]])
-
Aug 7th, 2001, 01:09 AM
#3
So basically, it goes something like this:
VB Code:
Private Sub cmdReplace_Click()
Dim sData As String
Dim FindString As String
Dim ReplaceWith As String
FindString = txtFindString.Text
ReplaceWith = txtReplaceWith.Text
Open "c:\Source.txt" For Input As #1
sData = Input(LOF(1), 1)
Close #1
sData = Replace(sData, FindString, ReplaceWith)
Open "c:\Target.txt" For Output As #2
Print #2, sData
Close #2
End Sub
-
Aug 7th, 2001, 01:13 AM
#4
That was a faster method, if you wish to use what you are currently using with Line Input, it can be done like this:
VB Code:
Private Sub cmdReplace_Click()
Dim sData As String
Dim sText As String
Dim FindString As String
Dim ReplaceWith As String
FindString = txtFindString.Text
ReplaceWith = txtReplaceWith.Text
Open "c:\Source.txt" For Input As #1
Do Until EOF(1)
Line Input #1, sData
sText = sText & sData & vbCrLf
Loop
Close #1
sText = Replace(sText, FindString, ReplaceWith)
Open "c:\Target.txt" For Output As #2
Print #2, sText
Close #2
End Sub
That would be another way. And also, opening a file, storing it in a variable, and closing it is probably much better than opening two files at once and finding/replacing text in one and writing to the other. Just less complicated .
-
Aug 7th, 2001, 05:56 AM
#5
Thread Starter
Junior Member
Thanks Matthew.
Thanks for your help mate. You couldn't have made it any clearer.
Vaastav.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|