Question

I hope someone can please help me with this. The VB script below is in Excel and creates a new Word document. The code will copy a picture from Excel into Word. Then it will create and position a TextBox over the picture. It will then put text in the TextBox. This code does work correctly.

Set wrdApp = CreateObject("Word.Application")
wrdApp.Visible = True
Set wrdDoc = wrdApp.Documents.Add

Sheets("Sheet1").Shapes("Picture1").Copy
wrdApp.Selection.Paste


With wrdDoc.Shapes.AddTextBox(msoTextOrientationHorizontal, 200, 150, 96, 50)
    .Select
    .Name = "TextBox1"
End With


With wrdApp.Selection
    .ShapeRange.Fill.Visible = 0
    .ShapeRange.Line.Visible = 0
    .TypeText Text:="My picture text"
End With

As mentioned, the above code does work. The problem is I need to put this in a loop to copy the picture again (an X number of times). When I write the code to put it in a loop, it will paste the additional picture within the TextBox because that was last selected. I somehow need to code something like the Ctrl + End keys so it will bring the curser to the end of the document and outside of the TextBox. I can't get that to work.

In order to do that I need to use this code:

Selection.EndKey Unit:=wdStory

So the proper place to insert it within the code should be this section, like what I have below:

With wrdApp.Selection
    .ShapeRange.Fill.Visible = 0
    .ShapeRange.Line.Visible = 0
    .TypeText Text:="My picture text"
    .EndKey Unit:=wdStory
End With

This gives me a VB error when I add that line in. Now if I copy this code into Word and run it from the Macro, it will work perfectly. However, this code is in Excel and has to create everything in Word.

Can someone please tell me how I can get it so it moves the curser out of the TextBox and to the end of the document? I know the issue is because the code is in Excel and trying to go to Word, there has to be some way to get it to work or a similar code using ASCII. I have tried everything I can think of and searched for hours for a solution.

Thanks for any help someone can provide,

Chris

Was it helpful?

Solution

If I understand your question correctly, this works for me:

With wrdapp.ActiveDocument
  .Range(.Range.Characters.Count, .Range.Characters.Count).Select
End With

Edit

Try this (add stuff, remove stuff, see what works):

With wrdapp.ActiveDocument
  .Range(.Range.Characters.Count, .Range.Characters.Count).Select
  .GoTo wdgotobookmark, name:="\EndOfDoc"
  Selection.Move wdCharacter, .Characters.Count
End With

OTHER TIPS

Though this might not be the ideal way to go, the code below will clear the selection in Word, moving the focus out of the textbox.

wrdApp.Activate
SendKeys "{ESC}"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top