Hi All,
Here where I work, we have a group of colleagues who by default like to work in MS Word. On the other hand, our systems frequently want to read MS Excel documents to import data. So, when I saw rhuman's query I realized that it is a task I want to master, as well.
How do I build one VBA program that opens both a MS Word Doc and an MS Excel xls file, with code to search the Word doc for a 'key word' (or sequence of characters), then, grab a block of text (such as a 9-digit code following the key word), copy it to the clipboard, toggle to excel, find the next row in the worksheet, paste the value, and repeat the process as needed until no more instances of the key word are found.
Here is the code I captured with Word's macro recorder; unfortunately, it did not record the window change to Excel, selection of the cell, the paste or the window change back to Word.
[vba]Sub Macro2()
'
' Macro2 Macro
' Macro recorded 7/29/08 by Ron McKenzie
'
Selection.Find.ClearFormatting
With Selection.Find
.Text = "ID:"
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
Selection.Find.Execute
Selection.EscapeKey
Selection.MoveRight Unit:=wdCharacter, Count:=1
Selection.MoveRight Unit:=wdCharacter, Count:=9, _
Extend:=wdExtend
Selection.Copy
'// At this point, I changed windows and pasted the ID$# (those
' 9 characters) in to the next empty row in an Excel worksheet.
'// How do I tell VBA to tell Excel to find that next row and paste
' the value?
'// Is it better to code this in Excel VBA (instead of Word VBA
' driving Excel VBA) ?
'// Further, it seems to me rather than repeating code, that I want
' to loop back to the
' top and repeat the process and let the error on selection.find.execute
' failing to find an instance of 'ID:' signal the end of processing.
Selection.Find.ClearFormatting
With Selection.Find
.Text = "ID:"
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindAsk
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
Selection.Find.Execute
Selection.MoveRight Unit:=wdCharacter, Count:=1
Selection.MoveRight Unit:=wdCharacter, Count:=9, Extend:=wdExtend
Selection.Copy
'// I had 4 ID:s in my word file so this block was repeated two more times;
' omitted to save space
End Sub
[/vba]
All advice, guidance, point outs of resources (PDF docs, KB article here, stuff on other websites) and other helps will be gratefully received.
Many Thanks!