Results 1 to 3 of 3

Thread: Macro to lookup data in Excel and move to Word

  1. #1

    Thread Starter
    New Member
    Join Date
    Dec 2010
    Posts
    3

    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.)

  2. #2
    PowerPoster
    Join Date
    Dec 2004
    Posts
    25,618

    Re: Macro to lookup data in Excel and move to Word

    is the workbook already open?
    assuming yes, something like
    vb Code:
    1. set wsht = getobject("workbookname.xls").sheets("sheet1")
    2. answer = wsht.Application.WorksheetFunction.VLookup("foo", wsht.Range("b13:c16"), 2)
    3. 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
    i do my best to test code works before i post it, but sometimes am unable to do so for some reason, and usually say so if this is the case.
    Note code snippets posted are just that and do not include error handling that is required in real world applications, but avoid On Error Resume Next

    dim all variables as required as often i have done so elsewhere in my code but only posted the relevant part

    come back and mark your original post as resolved if your problem is fixed
    pete

  3. #3

    Thread Starter
    New Member
    Join Date
    Dec 2010
    Posts
    3

    Re: Macro to lookup data in Excel and move to Word

    Thanks, that looks like exactly what I need. Appreciate the help.

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width