Excel VBA to cycle through Word bookmarks and insert ranges (text, graphs & tables)

  • Hello everyone - I have managed to use Mr. Plow's fantastic script for using a VBA script to cycle through Word bookmarks and insert Excel range value. I have managed to get the script to work fantastically on text only copies. However I would also like to copy and paste charts as well as tables from named ranges. I was wondering how I could achieve this with a modification of the script that is found in this thread:


    http://www.ozgrid.com/forum/showthread.php?t=148798&page=1 (post number 6)


    Currently when I try to "autocopy" from a range that is a table I get the error: "Run-time error '94': "Invalid use of Null" on the following line:
    strValue = Trim(Application.Range(strName).Text)


    I don't believe it should be too hard to modify the script, but all my attempts have failed so far. If someone could advise me at least where I could start looking that would be fantastic.

  • Re: Excel VBA to cycle through Word bookmarks and insert ranges (text, graphs & table


    I had a project where I created a Report with data from Excel and this code worked well. There should be enough to give you some hints on the format.


    Code
    Set ScoreTitle = Range("ScoreTitle1")
        objDoc.Bookmarks.Item("ScoreTitle").Range.InsertAfter ScoreTitle
        appWrd.Selection.Goto What:=wdGoToBookmark, Name:="ScoreDistributionChart"
        ThisWorkbook.Sheets("Score Distribution").ChartObjects(1).Copy
        appWrd.Selection.Paste
        appWrd.Selection.ParagraphFormat.Alignment = wdAlignParagraphCenter



    Code
    appWrd.Selection.Goto What:=wdGoToBookmark, Name:="BookmarkName"
            ThisWorkbook.Sheets("SheetName").Activate
            Range("A1").Select
            ActiveCell.CurrentRegion.Copy
            appWrd.Selection.Paste
            appWrd.Selection.Tables(1).Rows.Alignment = wdAlignRowCenter
  • Re: Excel VBA to cycle through Word bookmarks and insert ranges (text, graphs & table


    Thanks for the extra code Richard. I still however have the issue with the current code that I am trying to run. I get stuck on this line with the code that I am using from the post that I referenced. It's fantastic code as it does the following:


    Looks for bookmarks in word document and lists them in memory. Finds ranges in excel with the same name. Automatically copies these ranges and re-inserts the bookmark. The code is SUPER fast and the formatting for text is fantastic. But I just don't understand how I can adapt it for use with tables and charts.


    This is the line I truly don't understand as to what it does and how to get around it:


    strValue = Trim(Application.Range(strName).Text)


    I keep on getting the error 94 and I am starting to go mad!

  • Re: Excel VBA to cycle through Word bookmarks and insert ranges (text, graphs & table


    Trim(strName) takes out any spaces from the string strName but it can only do that if strName has been assigned a value, so ask how does strName get its value. You need to step through the code one line at a time using the F8 function key on your keyboard, when you mouse over a variable you should see a value appear or you can bring up the Locals window to see what has been assigned to each variable at each stage of the program. If you are still having problems attach a file so I can get a better picture of what you are trying to do.


    Richard

  • Re: Excel VBA to cycle through Word bookmarks and insert ranges (text, graphs & table


    Thanks again for all your support Richard.


    I went and cycled through the code as you suggested. The issue I am having is that the tables and charts I am trying to copy are not text. So I end up with this part of the code giving me a null value:


    (Application.Range(strName).Text)


    I somehow need to be able to distinguish between text, charts and tables in order to be able to copy them into my report. Unfortunately I am still very much a beginner at coding VBA and am unsure of how this can be best achieved.


    strName in this case is the Named Range/Bookmark for the table in the report (ARTableFruit in the attached example).

  • Re: Excel VBA to cycle through Word bookmarks and insert ranges (text, graphs & table


    Your homework? tut tut tut
    Attached is the Excel workbook with new code in Module 2 and a word template that must live in the same folder. NOTE you must rename Fruit1.doc to Fruit1.dotx. I couldn't see the file with the new extension in the attachment portal and had to rename it to Fruit1.doc
    This is slightly different in that it uses a template. Make a copy of the template, it is easy to end up with an open file when your code crashes and does not close the Word file, always manually open and close the Word file after a crash to ensure its closed properly.
    You can add error trapping and any other functionality as needed.
    You'll note how different my simple code is compared to Mr Plows. He obviously had a need to do what he did, your trying to adapt his code without understanding it caused you grief. That said someone better than me would likely critique my code, we're all learning.


    Regards
    Richard


    The code for those interested:


  • Re: Excel VBA to cycle through Word bookmarks and insert ranges (text, graphs & table


    Hello Richard. Many thanks for your support. Actually the document I put together was just an example of what I need to be able to do.


    Your code is nice and I can understand most of it. Unfortunately it doesn't quite do what I need it to. I'm really sorry to say this as I really appreciate all your help that you have provided me so far.

    The nice thing about the code that Mr. Plow provided is that you don't need to manually provide all the bookmark names and named ranges and is very universal. The word document that I use in combination with the Excel file might not just be created once, but also updated if any changes occur in the word document. There are quite a lot of tables and charts in the report. Sometimes some of the tables might be removed as they are not required and then the corresponding bookmark would be removed too - so I can't go around updating the VBA manually as this would take more time than a manual copy paste job.


    I'm scratching my head at the moment as to what I can do to make some universal code that will work nicely with updating and also to copy charts and tables. I've bought myself Excel VBA for Dummies and have now started reading that in the hope of being able to come up with a nice solution.


    I'll definitely come back here when I have a result. If you (Richard), or anyone else, has any further ideas I am always appreciative.


    Thanks so much for all your help and support!

  • Re: Excel VBA to cycle through Word bookmarks and insert ranges (text, graphs & table


    So that we are not guessing, make a list of several scenarios of what you might be faced with. If you have a variable number of Text, Tables & Charts how did you propose that Excel would grab them. Its a bit hard not seeing the full picture.

  • Re: Excel VBA to cycle through Word bookmarks and insert ranges (text, graphs & table


    Hello Richard.


    I know that Excel can grab all Named Ranges. So I have around 10 tables that need copying from Excel to word and around 10 charts that need copying too. Added to that there are probably around 10 text strings that need copying. Ideally I could do it by loading the list of bookmarks from Word:


    Code
    With wdDoc        ReDim sbkmk(1 To .Bookmarks.Count)
             
             'populates array (a list) with bookmark names
            For tmp1 = 1 To .Bookmarks.Count
                sbkmk(tmp1) = .Bookmarks(tmp1).Name
            Next


    So now I have the list of bookmarks in the word document where I would like to insert various bits of text, tables or graphs from my Excel document. If the bookmark has the same name as a named range I should be able to match these.


    I know that I can load the text in a String as the code by Mr. Plow does this. I was wondering if there is a way that I can load an excel chart into something like a string or a variable, hold it in memory and then dump it into where the word document bookmark is.


    I know what format each Bookmark is going to be in so I could create a list something like this:


    Code
    'Insert all text items
    For "ARText1", "ARText2", "ARText3" etc.
         Use Function "Insert Text"  
    'Insert all chart items
     For "ARChart1", "ARChart2", "ArChart3" etc. 
         Use Function "Insert Chart"
    'insert all tables
    For  "ARTable1", "ARTable2", "ArTable3" etc. 
         Use Function "Insert Table"


    (This is obviously not real code)


    Mr Plow uses the following Function to insert text, so we have this covered:



    The important part of this function is that it re-adds the bookmark allowing the user to update the word document at a future point in time. So the bookmark needs to cover the entire word, chart or table when updating.


    The biggest problem I have with Mr Plow's code is the following item:


    Code
    strValue = Trim(Application.Range(strName).Text)


    I am unsure of how one could modify this code to work with charts or tables, or whether that is even possible or not.

  • Re: Excel VBA to cycle through Word bookmarks and insert ranges (text, graphs & table


    So why not use a template that has the bookmarks placed where you want your content, everytime you want to update the document just rewrite it from Excel, have as much variable content in Excel as you can, have content that never changes in the template, have purposely named bookmarks in the right sections of your template.
    If you have different content at different times write code that allows a selection process ie a userform with checkboxes. Send only the text, charts & tables you want to their respective bookmarks, at worst you have to go into the finished document and do a little formatting ie delete blank pages where the bookmarks wern't populated. Consider also a system where you could have numerous templates with the bookmarks placed in different ways or order to select from.
    Thats just my opinion, I find I develop a system, get it going and then look for ways to improve it. In this way you learn a bit more about the complete picture rather than trying to develop the perfect system straight up and then realising issues. I have no doubt there is scope to build a system thats smart about collecting and assigning range names to bookmarks.
    The code I provided will do what you need, you just have to build in some If statements around selection of content.
    If I had time I would setup Mr Plows code and step through it to understand where you are having issues with that line of code, strName is obviously not getting a value earlier on in the procedure.
    Hope this helps.
    Richard

  • Re: Excel VBA to cycle through Word bookmarks and insert ranges (text, graphs & table


    Hi Richard. I just wanted to let you know that I managed to do it!!! I can now copy and paste tables and text with great formatting results. All there needs to be is a bookmark in the word document and a named range in excel with the same.


    I will post the code here shortly. It's a bit of a mess at the moment and could probably really do with a good clean-up. I'll try as best I can to make the code readable and then post it here in the next couple of days.

  • Re: Excel VBA to cycle through Word bookmarks and insert ranges (text, graphs & table


    Please be prepared for some horrendously crap code:





    It's bloody horrible, but it works very well. Any questions give me a shout!

  • Re: Excel VBA to cycle through Word bookmarks and insert ranges (text, graphs & table


    Well done, when I have a chance I will play with it and comment. Does this make you the Geek of your department!

  • Re: Excel VBA to cycle through Word bookmarks and insert ranges (text, graphs & table


    Just noticed that there is a small error in the code:
    wdApp.WordBasic.OpenOrCloseParaBelow


    needs to be:


    wdApp.WordBasic.CloseParaBelow


    And yes, it totally makes me the geek of my department. But they love me for it, as what used to take half an hour of BORING copy + paste jobs now can be done in 30 seconds. Reports can be generated really quickly with less errors :D

  • Re: Excel VBA to cycle through Word bookmarks and insert Excel range value


    [EDIT - moved from other thread]
    I know this discussion has jumped over to another thread so I'm going to link them together here: http://www.ozgrid.com/forum/showthread.php?t=157163&page=1.


    I have pulled all this code from many sources and can take personal credit for very little of it.


    The PopulateWordBookmarks sub has been improved to separate out bookmarks that are text and those that are charts/graphs. I've done this by beginning the names of my excel ranges that I want to be pictures with "chart". The process takes all the ranges beginning with "chart" and saves as a temporary .gif, then attempts to import that .gif file INTO the bookmark. Currently struggling with INTO and not AT.


    Here is relevant code (suppressing some of the duplicative stuff previously posted):



    The FillBookmark sub used for any ranges that do not begin with "chart" remains unchanged.


    The FillBookmarkImage sub is trying to delete all prior images and text from a bookmark, then replace with the new image. Right now it's inserting pictures AFTER the bookmark:



    Thanks for the help.

  • Re: Excel VBA to cycle through Word bookmarks and insert ranges (text, graphs & table


    I didn't have any success with the code above. [EDIT - See above] I have posted some updated and additional code in the original thread here, http://www.ozgrid.com/forum/sh…48798&p=572856#post572856. I too am trying to get to the bottom of this issue. Main issue still left is removing existing images in a bookmark before inserting the new image INTO the bookmark (as opposed to AFTER the bookmark).

  • Re: Excel VBA to cycle through Word bookmarks and insert ranges (text, graphs & table


    Hi there Mr Plow. What issues are you having with the code? What version of Excel and Word are you running?


    I will upload an example word and excel document when I get into the office for you to play around with that works on my end. I've tested the code in Office 2007. I've tried running it on my home computer (Office 2010) but there is a small problem with pasting charts.

  • Re: Excel VBA to cycle through Word bookmarks and insert ranges (text, graphs & table


    I found some more errors in the code above. Please see the following downloads for some more slightly better code:
    http://dl.dropbox.com/u/15735073/Permanent/Fruit.docx
    http://dl.dropbox.com/u/15735073/Permanent/Fruit.xlsm


    http://"http://dl.dropbox.com/u/15735073/Permanent/Fruit.xlsm"Edit: Just documented the hell out of the code. Same download.


    I thought I would add the pretty much final code here, as the files might be removed at some point in time.


  • Re: Excel VBA to cycle through Word bookmarks and insert ranges (text, graphs & table


    Running Excel 2007 and Word 2007. An Office 2010 upgrade is probably not too far off in the future so hopefully final code will be usable in both versions.


    I'm trying to import images into the bookmark, not charts. The reason is because I'm using my excel file for projections and other purposes after creating the Word reports. This will make the linked charts in Word change which I don't want. By first saving the Excel chart as a picture and then importing the picture into the bookmark, I don't have to worry about my Word report changing when my spreadsheet later does.

Participate now!

Don’t have an account yet? Register yourself now and be a part of our community!