[2008] Replacing. Is this the best way ?
Hello to all...
I wana ask you if you think that's the best and the fastest way to replace <<words>> into a .doc file?
I don't know other way and i think mine is too slow for doing this kind of job.
Code:
Dim word As New Microsoft.Office.Interop.Word.Application
Dim doc As Microsoft.Office.Interop.Word.Document
Try
doc = word.Documents.Open(System.Windows.Forms.Application.StartupPath & "\cdmf.mbm")
doc.Activate()
Dim myStoryRange As Microsoft.Office.Interop.Word.Range
For Each myStoryRange In doc.StoryRanges
With myStoryRange.Find
.Text = "<<filiala>>"
.Replacement.Text = Me.txt_filiala.Text
.Wrap = Microsoft.Office.Interop.Word.WdFindWrap.wdFindContinue
.Execute(Replace:=Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll)
End With
With myStoryRange.Find
.Text = "<<data>>"
.Replacement.Text = Me.txt_data_cm.Text
.Wrap = Microsoft.Office.Interop.Word.WdFindWrap.wdFindContinue
.Execute(Replace:=Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll)
End With
With myStoryRange.Find
.Text = "<<seriacm>>"
.Replacement.Text = Me.txt_seria_cm.Text
.Wrap = Microsoft.Office.Interop.Word.WdFindWrap.wdFindContinue
.Execute(Replace:=Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll)
End With
With myStoryRange.Find
.Text = "<<nrcm>>"
.Replacement.Text = Me.txt_nr_cm.Text
.Wrap = Microsoft.Office.Interop.Word.WdFindWrap.wdFindContinue
.Execute(Replace:=Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll)
End With
With myStoryRange.Find
.Text = "<<numeprenume>>"
.Replacement.Text = Me.txt_nume_prenume.Text
.Wrap = Microsoft.Office.Interop.Word.WdFindWrap.wdFindContinue
.Execute(Replace:=Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll)
End With
Next myStoryRange
doc.SaveAs(System.Windows.Forms.Application.StartupPath & "\cdm\" & "\" & Me.txt_cnp.Text & "\" & Me.txt_nr_cm.Text & ".mbm")
doc.Close()
doc = Nothing
Catch ex As Exception
MessageBox.Show("Error opening.")
End Try
I'm waiting your opinions and... Thanks in advice...
Re: [2008] Replacing. Is this the best way ?
I don't see anything explicitly wrong with your code. The only optimization you might be able to add is that I don't think you need to loop through the Stories in a document to do a replace like this. It has been a while since I have done a replace, but I think you can do something that works across the whole document.
Are you seeing performance problems with the code that would indicate a problem with performance?
Re: [2008] Replacing. Is this the best way ?
For replacing 20 words takes up to 15-20 seconds.
All the code works under BackGroundWorker and if a user is giving another command for replace then will interrupt the current replacing job.
Whats the best way to do it ?