将 VBA 生成的图表定位在 Word 文档中的表格下方时出现问题

问题描述 投票:0回答:1

我在 Microsoft Word 中从 VBA 宏生成图表时遇到问题。我有一个宏,可以根据 Word 文档中特定表(表 n°12)中的数据生成直方图。我的目标是将此图表放置在从中提取数据的表 12 的下方。

我尝试使用 Top 属性设置图表的垂直位置,但我不断收到以下错误消息:“参数数量错误或属性分配无效。

这是我当前宏的代码:

Option Explicit

Sub CreateWordChart3()
    Dim oChart As Chart, oTable As Table
    Dim oSheet As Excel.Worksheet
    Dim oShape As Shape
    Const START_CELL = "AA1"
    
    Application.ScreenUpdating = False
    
    ' Récupérer la table 12 du document
    Set oTable = ActiveDocument.Tables(12)
    
    ' Ajouter le graphique en tant que forme au document
    Set oShape = ActiveDocument.Shapes.AddChart2(-1, xlColumnClustered)
    
    ' Définir la position du graphique sous la table 12
    With oShape
        .Top = oTable.Range.Tables(1).Rows(oTable.Rows.Count).Range.End(wdParagraph).Information(wdVerticalPositionRelativeToPage)
        .Left = oTable.Range.Left
    End With
    
    ' Obtenir le graphique en tant qu'objet Chart
    Set oChart = oShape.Chart
    
    ' Copier les données de la table dans une feuille Excel temporaire
    oTable.Range.Copy
    Set oSheet = oChart.ChartData.Workbook.Worksheets(1)
    oSheet.Range(START_CELL).PasteSpecial Paste:=xlPasteValuesAndNumberFormats
    
    ' Créer le tableau 2D
    Call Create2DTable(oSheet, oSheet.Range(START_CELL))
    
    ' Fermer le classeur Excel temporaire
    oChart.ChartData.Workbook.Close
    
    Application.ScreenUpdating = True
End Sub

我正在寻求有关如何将图表正确放置在 Word 文档中指定表格下方并解决错误消息的建议。任何帮助或建议将不胜感激。预先感谢您!

vba ms-word histogram
1个回答
0
投票
  • 将图表形状转换为
    InlineShape
    并移动到所需位置
Sub CreateWordChart4()
    Dim oChart As Chart, oTable As Table
    Dim oSheet As Excel.Worksheet
    Dim oShp As Shape, afterTblRange As Range
    Const START_CELL = "AA1"
    Application.ScreenUpdating = False
    Set oTable = ActiveDocument.Tables(2)  ' modify as needed
    Set oShp = ActiveDocument.Shapes.AddChart
    Set oChart = oShp.Chart
    Set oSheet = oChart.ChartData.Workbook.Worksheets(1)
    oTable.Range.Copy
    oSheet.Range(START_CELL).Select
    oSheet.Paste
    Call Create2DTable(oSheet, oSheet.Range(START_CELL))
    oChart.ChartData.Workbook.Close
    
    Set afterTblRange = oTable.Range
    afterTblRange.Collapse Direction:=wdCollapseEnd
    oShp.ConvertToInlineShape
    oShp.Select
    Selection.Cut
    afterTblRange.PasteAndFormat wdPasteDefault
    Application.ScreenUpdating = True
End Sub

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.