Home » excel » excel – Move the cursor in a textbox in Word

excel – Move the cursor in a textbox in Word

Posted by: admin April 23, 2020 Leave a comment

Questions:

I am trying to use VBA to paste a chart from Excel to a text box (in line with text) in Word.

I find that when I paste just after selecting the text box, the chart will be pasted above the text box instead of in the text box. To paste it in the text box I have to move the cursor in the box first.

Knowing that, I read that SetFocus can move the cursor in the text box; however I got an error message “Method or data member not found” at the line of SetFocus.

Could any one help me to move the cursor in the text box?

Below is what I used for copying and pasting:

xlsfile.ActiveChart.ChartArea.Copy    'Copying has no problem
ActiveDocument.Shapes(boxName).SetFocus      'I cannot find the function in the suggested function list
Selection.PasteSpecial DataType:=wdPasteBitmap
How to&Answers:

Logic I used:

  1. Export Chart to user’s temp directory as image
  2. Insert the image in the textbox using Shp.Fill

Is this what you are trying?

Private Declare Function GetTempPath Lib "kernel32" Alias "GetTempPathA" _
(ByVal nBufferLength As Long, ByVal lpBuffer As String) As Long

Private Const MAX_PATH As Long = 260

Sub Sample()
    '~~> Excel Objects/Variables
    Dim objChrt As ChartObject
    Dim myChart As Chart
    Dim imgFileName As String

    '~~> Word Objects/Variables
    Dim oWordApp As Object, oWordDoc As Object
    Dim FlName As String

    '~~> Change this to relevant sheet and graph
    Set objChrt = ThisWorkbook.Sheets("Sheet1").ChartObjects(1)
    Set myChart = objChrt.Chart

    imgFileName = TempPath & "myChart.png"

    '~~> Export Graph as image
    myChart.Export Filename:=imgFileName, Filtername:="PNG"

    '~~> This is your word document which has the textbox
    FlName = "C:\Users\Siddharth\Desktop\DeleteMeLater.Docx"

    '~~> Create Word application object
    Set oWordApp = CreateObject("Word.Application")
    oWordApp.Visible = True

    '~~> Open your word file
    Set oWordDoc = oWordApp.Documents.Open(FlName)

    '~~> Insert Image in the textbox
    oWordDoc.Shapes(1).Fill.UserPicture (imgFileName)

    '~~> Kill the temp file
    Kill imgFileName
End Sub

'~~> Function to get user's temp directory
Function TempPath() As String
    TempPath = String$(MAX_PATH, Chr$(0))
    GetTempPath MAX_PATH, TempPath
    TempPath = Replace(TempPath, Chr$(0), "")
End Function

Screenshot

Before

enter image description here

After

enter image description here

NOTE:

In the above code, I have shown how to do this from MS-Excel. With minor edits, you can do it from MS-Word as well.

Answer:

Finally, these two lines did the job! Thanks everybody!

ActiveDocument.Shapes(boxName).Select
Selection.ShapeRange.TextFrame.TextRange.Select