Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

In Word VBA, how to combine one selection to another selection executed from find

Posted on 2016-09-24
10
Medium Priority
?
57 Views
Last Modified: 2016-09-25
I have a document where question and answer have different styles assigned to each (for question "*Questions" and for answer "Normal"), answer can have multiple paragraphs or even image, so basically I need code to find/search a particular word in document and when found, code need to select from start of that question till the end of its answer (or start of next question). I have code in break but somehow could not able to compile it (not able to combine selection form Previous_Question till Next_Question). code goes like this:

 Sub Previous_Question()

 Selection.Find.Style = "*Questions"
 Selection.Find.Forward = False
 Selection.Find.Execute

 End Sub

 Sub Next_Question()

 Selection.Find.Style = "*Questions"
 Selection.Find.Forward = True
 Selection.Find.Execute

 End Sub


 Sub Find_Word()

 Selection.Find.ClearFormatting
 With Selection.Find
 .Text = InputBox(sPrompt, sTitle, sDefault)
 End With
 Do While Selection.Find.Execute
 Selection.StartOf Unit:=wdParagraph

 Selection.MoveEnd Unit:=wdParagraph
 sBigString = sBigString + Selection.Text
 Selection.MoveStart Unit:=wdParagraph
 Loop
 Documents.Add DocumentType:=wdNewBlankDocument
 Selection.InsertAfter (sBigString)

 End Sub

Open in new window

Please help!!!

Edit: Code put into a snippet box using the CODE item in the comment editor toolbar. GrahamSkan
0
Comment
Question by:Ashish Bist
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 6
  • 4
10 Comments
 
LVL 76

Expert Comment

by:GrahamSkan
ID: 41813748
I isn't clear what you are trying to do in the Find_Word procedure , but I suppose that you are trying to gather all the paragraphs containing the chosen word and copy them to a new document.

I usually recommend not using the Selection object in macros, where possible, but you might have a special reason to use the Selection as input by the user.

I tested this code on a blank document after typing =RAND(5,5), Enter. This creates some paragraphs some of which contain the word 'create' which I have set as the default in the Input box.
Sub Find_Word()
Dim sBigstring As String
Dim sPrompt As String
Dim sTitle As String
Dim sDefault As String
Dim doc As Document

sPrompt = "Please type in the text"
sTitle = "Text"
sDefault = "create"

ActiveDocument.Select
Selection.Find.ClearFormatting
With Selection.Find
.Text = InputBox(sPrompt, sTitle, sDefault)
    Do While .Execute
        Selection.StartOf Unit:=wdParagraph
        Selection.MoveEnd Unit:=wdParagraph
        sBigstring = sBigstring + Selection.Text
        Selection.MoveStart Unit:=wdParagraph
    Loop
End With

Set doc = Documents.Add
doc.Range.Text = sBigstring

End Sub

Open in new window

0
 

Author Comment

by:Ashish Bist
ID: 41813833
Hi Graham,

Thanks for the code, though, I was more looking for the other part of the query, after getting the input from input box, I need the code to go to start of the question which the input is part of till the next question starts. I will quote the example below, If I will search, "Manage Scheduled" and then when found in question number "1", it should copy from question start to end of the answer (1 to page) for question 1 and then search another instance and do the same thing, copy from start of the question to end of the answer. Hope I am more clear this time.

1. Can I use e-Monies NEFT for foreign remittances?
This is a service designed only for remitting Indian Rupees within India.

Upon receiving a bill, HDFC Bank will immediately schedule the bill for payment. The bill will be paid around 7 working days before the bill due date. All bills scheduled for payment can be viewed and stopped by going to the on the "Manage Scheduled Bills" page

2. What is IFSC? How is it different from the MICR code?

IFSC stands for ‘Indian Financial System Code’. It is an 11 digit, alpha numeric code designed to identify bank branches in India. The MICR code uses 9 digits to identify bank branches.

3. Is the e-Monies NEFT system better than the existing RBI-EFT system?

E-Monies NEFT has no restrictions, because it’s based on a centralized network. That’s not the case for the RBI-EFT system, which is confined to just 15 centres.

4. What information is required to use the e-monies NEFT service?

To use this service, you should provide the beneficiary details (name and account number), and the name and IFSC of the beneficiary bank branch.

5. If the money is not credited to the beneficiary’s account while using the e-monies NEFT service, will I get it back?

Your funds will be returned to your account if they are not credited.

6. How does the e-monies NEFT service differ from RGTS and EFT?

E-Monies NEFT is an electronic payment system, used to transfer funds to any part of India. It works on ‘net settlement’, unlike RTGS that works on ‘gross settlement’, and EFT which is restricted to only 15 centres.
0
 

Author Comment

by:Ashish Bist
ID: 41813848
Also I managed to write the code for going to start of the question and to the start of the next question style individually with below codes but cannot able to extend the selection or combine the those codes to select combine part of question and its respective answer.

Sub Previous_Question()
 Selection.Find.Style = "*Questions"
 Selection.Find.Forward = False
 Selection.Find.Execute

 End Sub

 Sub Next_Question()
 Selection.Find.Style = "*Questions"
 Selection.Find.Forward = True
 Selection.Find.Execute

 End Sub

I have a document where question and answer have different styles assigned to each (for question "*Questions" and for answer "Normal"), and answer can have multiple paragraphs or even image
0
New benefit for Premium Members - Upgrade now!

Ready to get started with anonymous questions today? It's easy! Learn more.

 
LVL 76

Expert Comment

by:GrahamSkan
ID: 41814035
You don't seem to have any geographic location information in your profile, so you might be surprised to learn that it is about 20:00, summer time, here in the UK, and I am winding down for the day.

Therefore I won't be trying any analysis for today. However, I strongly advise you to post a sample document, so that we know what we are dealing with. I will try to look at in my morning.
0
 

Author Comment

by:Ashish Bist
ID: 41814292
Hi Graham,

Thanks for looking into it, I got the code moving for one find instance but not able to figure out how can make it work all the find results in the document. I have attached the test file for your kind perusal and below is the code I am trying. Example from the test case would be, if I try find "Manage Scheduled" through the code below, it is copying it to the new file for 1st search of "Manage Scheduled" in question 1 but I need the same thing replicated for other instances as well where it is there as a part of answer like question2 and 5. Hope I have explained it better. I am not able to loop it, where to place the loop? I cornered it as a message in the below code so that rest of the code will work for you to understand what I am trying to achieve with the below code. Thanks Ashish

Sub Test1()

Dim rng1 As Range
Dim rng2 As Range
Dim rngFound As Range
Dim sBigstring As String
Dim sPrompt As String
Dim sTitle As String
Dim sDefault As String
Dim doc As Document

sPrompt = "Please type in the text"
sTitle = "Text"
sDefault = "create"

ActiveDocument.Select
Selection.Find.ClearFormatting
With Selection.Find
.Text = InputBox(sPrompt, sTitle, sDefault)
.Execute
End With
'Selection.StartOf Unit:=wdParagraph

Selection.Collapse
'Do While Selection.Find.Execute
With Selection.Find
    .ClearFormatting
    .Replacement.ClearFormatting
    .Text = ""
    .Replacement.Text = ""
    .Forward = True
    .Wrap = wdFindStop
    .Format = False
    .MatchCase = False
    .MatchWholeWord = False
    .MatchWildcards = False
    .MatchSoundsLike = False
    .MatchAllWordForms = False
 End With


Selection.Find.Style = "*Questions"
Selection.Find.Forward = False
Selection.Find.Execute

Set rng1 = Selection.Range

With Selection.Find
    .ClearFormatting
    .Replacement.ClearFormatting
    .Text = ""
    .Replacement.Text = ""
    .Forward = True
    .Wrap = wdFindStop
    .Format = False
    .MatchCase = False
    .MatchWholeWord = False
    .MatchWildcards = False
    .MatchSoundsLike = False
    .MatchAllWordForms = False
 End With


Selection.Find.Style = "*Questions"
Selection.Find.Forward = True
Selection.Find.Execute

Set rng2 = Selection.Range

Set rngFound = ActiveDocument.Range(rng1.Start, rng2.Start)
            strTheText = rngFound.Text
            'MsgBox strTheText

sBigstring = sBigstring + strTheText
'Selection.MoveStart Unit:=wdParagraph
'Loop
Documents.Add DocumentType:=wdNewBlankDocument
Selection.InsertAfter (strTheText)

End Sub
0
 

Author Comment

by:Ashish Bist
ID: 41814298
Final solution should throw the below result in a new document after executing search for "Manage Scheduled", as it is present on question1,2, 5.

1.      Can I use e-Monies NEFT for foreign remittances?

This is a service designed only for remitting Indian Rupees within India.
Upon receiving a bill, HDFC Bank will immediately schedule the bill for payment. The bill will be paid around 7 working days before the bill due date. All bills scheduled for payment can be viewed and stopped by going to the on the "Manage Scheduled Bills" page

2. What is IFSC? How is it different from the MICR code?


IFSC stands for ‘Indian Financial System Code’. It is an 11 digit, alpha numeric code designed to identify bank branches in India. The MICR code uses 9 digits to identify bank branches.
Manage Scheduled does something and something and then something.

5. If the money is not credited to the beneficiary’s account while using the e-monies NEFT service, will I get it back?

Your funds will be returned to your account if they are not credited.
Manage Scheduled does something and something and then something.
Some text will go here, how to do online trading, something and something.
0
 
LVL 76

Accepted Solution

by:
GrahamSkan earned 2000 total points
ID: 41814615
So is the objective to find the chosen text in the answer and to copy each such answer and its preceding question to the new document? See if this helps:
Sub QuestionsAndAnswers()
Dim sBigstring As String
Dim sPrompt As String
Dim sTitle As String
Dim sDefault As String
Dim docA As Document
Dim docB As Document
Dim strPhrase As String
Dim rng As Range
Dim rngAnswer As Range
Dim rngQuestion As Range

Set docA = ActiveDocument
sPrompt = "Please type in the text"
sTitle = "Text"
sDefault = "Manage Scheduled"

strPhrase = InputBox(sPrompt, sTitle, sDefault)
If Len(strPhrase) > 0 Then
    Set rng = docA.Range
    
    With rng.Find
        .Text = strPhrase
        .Style = "Answer"
        Do While .Execute
            Set rngAnswer = rng.Duplicate
            rngAnswer.Expand wdParagraph
            Debug.Print "Answer", rngAnswer.Start, rngAnswer.End
            Set rngQuestion = rngAnswer.Duplicate
            rngQuestion.Start = docA.Range.Start 'look back from answer start
            rng.Start = rngAnswer.End 'avoid duplicate finds in same answer paragraph
            With rngQuestion.Find
                .Style = "Question"
                .Forward = False
                If .Execute() Then
                    If docB Is Nothing Then
                        Set docB = Documents.Add
                    End If
                    rngQuestion.Copy
                    docB.Bookmarks("\EndOfDoc").Range.Paste
                    rngAnswer.Copy
                    docB.Bookmarks("\EndOfDoc").Range.Paste
                Else
                    MsgBox "Question before not found"
                    End
                End If
            End With
        Loop
    End With

    If docB Is Nothing Then
        MsgBox strPhrase & " not found"
    End If
End If
End Sub

Open in new window

1
 

Author Closing Comment

by:Ashish Bist
ID: 41814619
That's perfect, exactly what I was looking for.  Thank you so very much.
0
 

Author Comment

by:Ashish Bist
ID: 41814659
Just one thing more, because you have it coded "rngAnswer.Expand wdParagraph", it is taking only first paragraph of the answer, can it be expanded for all part of the answer? Like it should give the below result for the 5th question but it is just giving me the one line with the "Manage Scheduled", please look into it when ever you get some free time. thank you Graham, you are a savior.

Your funds will be returned to your account if they are not credited.
Manage Scheduled does something and something and then something.
Some text will go here, how to do online trading, something and something.
0
 
LVL 76

Expert Comment

by:GrahamSkan
ID: 41815024
Previously, we were working on the assumption that all the answers and all the questions comprised one paragraph each. While we can extend the current techniques in the light of the new information, it will add considerably more complexity - so much so that perhaps a more basic method would be better. Remember that complexity is the antithesis of maintainability.

I am thinking of simply stepping through the paragraphs, examining their style and checking the contents using VB string methods. This would be instead of using the .Find objects. Whether it would be more performant or not will depend on the size of the document and usual frequency of the searched-for text. Can you give any indication of this?
0

Featured Post

On Demand Webinar - Networking for the Cloud Era

This webinar discusses:
-Common barriers companies experience when moving to the cloud
-How SD-WAN changes the way we look at networks
-Best practices customers should employ moving forward with cloud migration
-What happens behind the scenes of SteelConnect’s one-click button

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Since upgrading to Office 2013 or higher installing the Smart Indenter addin will fail. This article will explain how to install it so it will work regardless of the Office version installed.
When you see single cell contains number and text, and you have to get any date out of it seems like cracking our heads.
Although Jacob Bernoulli (1654-1705) has been credited as the creator of "Binomial Distribution Table", Gottfried Leibniz (1646-1716) did his dissertation on the subject in 1666; Leibniz you may recall is the co-inventor of "Calculus" and beat Isaac…
Have you created a query with information for a calendar? ... and then, abra-cadabra, the calendar is done?! I am going to show you how to make that happen. Visualize your data!  ... really see it To use the code to create a calendar from a q…

660 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question