我正在尝试使用VBA将Excel中的图表粘贴到Word中的文本框(与文本一致)。
我发现当我在选择文本框后粘贴时,图表将粘贴在文本框上方而不是文本框中。要将其粘贴到文本框中,我必须先将光标移动到框中。
知道了,我读到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
答案 0 :(得分:1)
使用的逻辑:
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进行编辑。
答案 1 :(得分:1)
最后,这两行完成了这项工作!谢谢大家!
ActiveDocument.Shapes(boxName).Select
Selection.ShapeRange.TextFrame.TextRange.Select