Macro to lookup data in Excel and move to Word
I have a spreadsheet with two columns of data - the index field and the actual data.
I want to open a Word document and be able to highlight some text, then run a macro which will pop over to Excel, look up the highlighted text in the index, copy the data cell, and insert it into the Word document.
I've tried doing this with the macro recorder but it doesn't work properly. Any help appreciated.
(So in my Excel sheet I have:
A1: "foo"
B1: "Data associated with foo."
In Word, I want to select "foo" and hit ctrl-whatever, and have "Data associated with foo." brought over.)
Re: Macro to lookup data in Excel and move to Word
is the workbook already open?
assuming yes, something like
vb Code:
set wsht = getobject("workbookname.xls").sheets("sheet1")
answer = wsht.Application.WorksheetFunction.VLookup("foo", wsht.Range("b13:c16"), 2)
set wsht = nothing
change foo to a variable of the selection.range.text, change range and column to suit
if you are using multiple times (especially if the workbook is not already open) keep the worksheet object in scope until finished with, rather than using getobject or createobject every time, place answer where required in word document
Re: Macro to lookup data in Excel and move to Word
Thanks, that looks like exactly what I need. Appreciate the help.