【问题标题】:VBA Macro to Paste Chart from Excel, into Word, and Format with Text WrappingVBA 宏将图表从 Excel 粘贴到 Word 中,并使用文本换行设置格式
【发布时间】:2018-09-13 18:03:01
【问题描述】:

在我的 excel 文档中,我有一个图表,我想将其复制并粘贴到 MS-Word 文档中。我想避免链接数据、嵌入工作簿和调整大小(Excel 将图表格式化为我想要的大小)。所以我想出了/发现以下几乎可以工作的代码:

Sub PasteChart()

Dim wd As Object
Dim ObjDoc As Object
Dim FilePath As String
Dim FileName As String
FilePath = "C:\Users\name\Desktop"
FileName = "Template.docx"


'check if template document is open in Word, otherwise open it
On Error Resume Next
Set wd = GetObject(, "Word.Application")
If wd Is Nothing Then
    Set wd = CreateObject("Word.Application")
    Set ObjDoc = wd.Documents.Open(FilePath & "\" & FileName)
Else
    On Error GoTo notOpen
    Set ObjDoc = wd.Documents(FileName)
    GoTo OpenAlready
notOpen:
    Set ObjDoc = wd.Documents.Open(FilePath & "\" & FileName)
End If
OpenAlready:
On Error GoTo 0

'find Bookmark in template doc
wd.Visible = True
ObjDoc.Bookmarks("LPPU").Select

 'copy chart from Excel
 Sheets("Group Level Graphs").ChartObjects("Chart 1").Chart.ChartArea.Copy

 'insert chart to Bookmark in template doc
 wd.Selection.PasteSpecial Link:=False, DataType:=14, Placement:=0, _
    DisplayAsIcon:=False

 End Sub

唯一的问题是图像被粘贴为“与文本对齐”,但我需要它是“带文本环绕的正方形”。我无法让 Word 或 Excel 记录将图像更改为“带文字环绕的正方形”。

PasteSpecial 部分仅用于放置wdFloatOverTextwdInLine,它们都不能解决此问题。

我对 VBA 非常陌生,并且已经没有想法了。我仍在尝试找到一种格式化它的方法,也许使用某种WITH 语句。但是,我想在继续 google-foo 并从 Youtube 学习 VBA 的同时尝试寻求帮助。

使用PasteAndFormat Type:=wdChartPicture 将图表链接到excel。所以这没有用。

【问题讨论】:

    标签: excel vba ms-word


    【解决方案1】:

    确保您在 VBE 中引用了 Word 应用程序,然后在常规粘贴 (wd.Selection.Paste) 之后立即添加这两行代码:

    wd.Selection.MoveStart word.WdUnits.wdCharacter, Count:=-1
    wd.Selection.InlineShapes(1).ConvertToShape.WrapFormat.Type = wdWrapSquare
    

    如果您想继续使用代码中的 PasteSpecial 方法,请将“wd.Selection.MoveStart...”上方的代码行替换为:

    wd.Selection.MoveEnd word.WdUnits.wdCharacter, Count:=1
    

    原因是常规粘贴将活动插入点留在插入对象的末尾。但如果使用 PasteSpecial 方法,则活动插入点位于粘贴对象的开头。为什么?我不知道! Word VBA 从未停止让我惊讶。 :-)

    【讨论】:

    • @Thomas,我已经根据您和我共享的 cmets 调整了上面的答案。 Stack Overflow 喜欢保持简短的注释字符串和最终的正确答案,以反映基于临时 cmets 所做的任何更改。一路走来,我正在清理我的 cmets。我建议你也这样做。此外,如果这个最终答案对您有用,我希望您将其标记为回答您的问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多