PDA

View Full Version : [SOLVED:] VBA for word



kissisvarmas
09-12-2016, 12:18 AM
Hi,

i am trying to use the below VBA code in a word to extract the whole sentence from the given string into another word document, but the problem is if the given strings are repeated in a single sentence, this code is extracting twice and pasting in other document, so my concern is to paste the sentense only single time, here the examples :
Code:

Sub Guidancefinal()


Const strFind As String = "outlook/guidance/forecast")
Dim guid1 As Document
Dim guid2 As Document
Dim vFind As Variant
Dim orng As Range, oText As Range
Dim i As Long
Set guid1 = Documents("Current.docx")
Set guid2 = Documents("Guidance.docx")
vFind = Split(strFind, "/")
guid2.Activate
Selection.WholeStory
Selection.Delete
For i = LBound(vFind) To UBound(vFind)
guid1.Activate
Set orng = ActiveDocument.Range
With orng.Find
Do While .Execute(FindText:=vFind(i))
Set oText = orng.Sentences(1)
oText.Select
Selection.Copy
guid2.Activate
Selection.EndKey wdStory
Selection.PasteAndFormat wdPasteDefault
orng.Collapse 0


Loop
End With
Next i
lbl_Exit:
Exit Sub


End Sub


case:
current document:
provided earnings guidance for the six months and forecast all the figures for period ended June 30, 2016. And results for reaming PEO’s

Guidance document:

provided earnings guidance for the six months and forecast all the figures for period ended June 30, 2016.
provided earnings guidance for the six months and forecast all the figures for period ended June 30, 2016.

here the issue is the code is extracting twice as the two strings are repeating in a single sentence, so i want to custom my program to extract as single line even we have a multi strings in the document


so please help me please

snb
09-12-2016, 01:53 AM
Ask you colleagues how to use VBA Code Tags in Forums.

Paul_Hossler
09-12-2016, 05:40 AM
Might be better to post your question in the Word forum, not the Excel one.

There's a lot of very helpful Word experts over there

gmayor
09-12-2016, 06:40 AM
The following should work (note there is no error check for missing documents)


Sub Guidancefinal()
Const strFind As String = "outlook/guidance/forecast"
Dim guid1 As Document
Dim guid2 As Document
Dim vFind As Variant
Dim orng As Range, oText As Range
Dim i As Long
Set guid1 = Documents.Open(FileName:="C:\Path\Current.docx", AddToRecentfiles:=False)
Set guid2 = Documents.Open(FileName:="C:\Path\Guidance.docx", AddToRecentfiles:=False)
vFind = Split(strFind, "/")
Set oText = guid2.Range
oText.Text = ""
For i = LBound(vFind) To UBound(vFind)
Set orng = guid1.Range
With orng.Find
Do While .Execute(FindText:=vFind(i))
oText.Collapse 0
oText.FormattedText = orng.Sentences(1).FormattedText
oText.InsertParagraphAfter
orng.Collapse 0
Loop
End With
Next i
lbl_Exit:
Exit Sub
End Sub

kissisvarmas
09-12-2016, 06:36 PM
Hi, Thanks for sending the code :)