Reputation: 11389
I would like to run a certain macro if a certain text has been typed and if F9 was pressed afterwards, for example:
The patient has been diagnosed with DIA1
, followed by the F9 key.
Word should react on the F9 key and run the macro DIA1 which would erase the word "DIA1" from the typed text and insert a certain text.
How could I do this?
Upvotes: 1
Views: 480
Reputation: 2556
Two things:
1- Solution finds "DIA1" within the last line, it doesn't check the last word. If you insist on the last word here it is:
Sub Lastword()
Dim rng As Range, wrd As String
Set rng = ActiveDocument.Paragraphs.Last.Range
wrd = StrReverse(Trim(Left(StrReverse(rng), InStr(1, StrReverse(rng), " ", vbTextCompare))))
MsgBox wrd
End Sub
2- F9-F12 are reserved so your closest option is F8. Alternatively you can assign macro to F9 by following these steps, as @Ibo suggested.
Solution:
1-Bind F8 to your macro
Sub Bind()
Application.CustomizationContext = ThisDocument.AttachedTemplate
KeyBindings.Add KeyCode:=BuildKeyCode(wdKeyF8), KeyCategory:=wdKeyCategoryMacro, Command:="Runme"
End Sub
2- "Find and replace" macro:
Sub Runme()
Dim rng As Range
Set rng = ActiveDocument.Paragraphs.Last.Range
rng.Find.Execute FindText:="DIA1", ReplaceWith:="hello", Replace:=wdReplaceAll
End Sub
3-If you need to unbind F8:
Sub Unbind()
CustomizationContext = NormalTemplate
FindKey(BuildKeyCode(wdKeyF8)).Clear
End Sub
Upvotes: 1
Reputation: 4299
You will need to define the macro that will trigger on F9 and then assign F9 to it. Learn How
Let's say the name of this macro will be ttt. I assume that when you press F9, you just typed the function name to run. Let's say DIA1. This is the structure you should follow. You need to add lines you need to replace the string DIA1 etc though, but this works. I tested myself
Sub DIA1()
MsgBox "hello"
End Sub
Sub ttt()
Selection.EndKey Unit:=wdLine
Selection.MoveLeft Unit:=wdWord, Count:=1, Extend:=wdExtend
Selection.Copy
Application.Run CStr(Selection)
End Sub
Upvotes: 0