在Word中的文本框中移动光标

我正尝试使用VBA将Excel中的图表粘贴到Word中的文本框(与文本一致)中。

我发现,当我刚select文本框后粘贴,图表将粘贴在文本框上方,而不是在文本框中。 要将其粘贴到文本框中,我必须首先将光标移动到框中。

知道了,我读了SetFocus可以在文本框中移动光标, 但是我在SetFocus的一行中收到错误信息“找不到方法或数据成员”。

任何人都可以帮我在文本框中移动光标吗?

以下是我用来复制和粘贴的内容:

 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 

我用的逻辑

  1. 将图表导出到用户的临时目录作为图像
  2. 使用Shp.Fill将图像插入文本框中

这是你正在尝试?

 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 

截图

之前

在这里输入图像说明

在这里输入图像说明

在上面的代码中,我已经展示了如何从MS-Excel中执行此操作。 通过小的编辑,你也可以从MS-Word中完成。

最后,这两条线做了这个工作! 谢谢大家!

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