Link to home
Start Free TrialLog in
Avatar of FaheemAhmadGul
FaheemAhmadGulFlag for United Kingdom of Great Britain and Northern Ireland

asked on

Macro that will open a Word Document based on the first two words of the paragraph in which the cursor currently is

I need help writing a macro that will open a pre-existing word document for me and make that newly opened document active document. The name of the file to be opened will be based on the first two words of the paragraph in which the cursor currently is plus the word medication.
So if the cursor is currently in the following paragraph:

Medical History
This is just a test paragraph to check if this macro
will open a new document for me based on the first two words of this paragraph which are Medical History in this case plus  the word Medication.

In the above case macro will open a document with the following path and name (C:\Test\Faheem Ahmad Medication).

Thanks for your help in anticipation.

Avatar of GrahamSkan
GrahamSkan
Flag of United Kingdom of Great Britain and Northern Ireland image

This is the basic idea. I'm not sure that it finds all illegal characters, but it does find the likely ones.
Sub OpenYetAnotherDoc()
    Dim strName As String
    Dim docAnother As Document
    Dim para As Paragraph
    
    Set para = Selection.Paragraphs(1)
    
    strName = para.Range.words(1).Text & para.Range.words(2).Text
    'remove (some) illegal characters
    strName = Application.CleanString(strName)
    strName = Replace(strName, Chr$(13), " ")
    strName = Replace(strName, Chr$(9), " ")
    strName = Replace(strName, "\", " ")
    strName = Trim$(strName)
    
    Set docAnother = Documents.Open("C:\test\" & strName & ".doc")
    docAnother.Activate
End Sub

Open in new window

Avatar of FaheemAhmadGul

ASKER

Many thanks for the prompt response to request for help. This works but requires a slight modification. The code above opens a document based on the first the two word the para where the cursor currently is. But I would like the name of file to be opened to be equal to the first two words of the para plus the word "Medication".
So if the first two words of the current para are "Medical History" I would like the path and the name of the file to be opened to be (C:\Test\ Medical History Medication).
ASKER CERTIFIED SOLUTION
Avatar of GrahamSkan
GrahamSkan
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Excellent. This is working fine now. Many thanks. Regards. Faheem
Excellent. This is working fine now. Many thanks