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
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
Logic I used:
- Export Chart to user’s temp directory as image
- Insert the image in the textbox using
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
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.
Finally, these two lines did the job! Thanks everybody!