生成单词表的直方图

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

我正在 Microsoft Word 中开发一个 VBA 宏,该宏应该根据 Word 文档中表格中的数据生成直方图(簇状列)。

我编写了以下代码来完成此任务:

Sub GenerateHistogram()
    Dim tbl As Table
    Dim rngData As Range
    Dim chartObj As Object

    ' Select the table containing the data
    Set tbl = ActiveDocument.Tables(1)

    ' Define the data range from the table
    Set rngData = tbl.Range

    ' Insert a chart into the document
    Set chartObj = ActiveDocument.Shapes.AddChart2(201, xlColumnClustered).Chart

    ' Add the data to the chart
    ' problem happens here
    chartObj.SetSourceData Source:=rngData, PlotBy:=xlColumns

    ' Adjust the size of the chart
    chartObj.Parent.Width = 400
    chartObj.Parent.Height = 300
End Sub

但是,当我运行此宏时,我收到“自动化错误,未指定错误”:

error

我已检查 Word 中是否启用了宏,并且我的表格格式是否正确。我不确定是什么导致了这个错误以及如何修复它。有人可以帮助我了解我的代码有什么问题以及如何纠正它吗?

任何帮助将不胜感激。预先感谢!

vba ms-word histogram
1个回答
0
投票
  • 在运行代码之前添加参考
    Microsoft Excel 
Option Explicit

Sub CreateWordChart()
    Dim oChart As Chart, oTable As Table
    Dim oSheet As Excel.Worksheet
    Dim RowCnt As Long
    Dim ColCnt As Long
    Dim LastColumn As String
    Application.ScreenUpdating = False
    Set oTable = ActiveDocument.Tables(1)
    Set oChart = ActiveDocument.Shapes.AddChart.Chart
    Set oSheet = oChart.ChartData.Workbook.Worksheets(1)
    'Determine size of table
    RowCnt = oTable.Rows.Count
    ColCnt = oTable.Columns.Count
    With oSheet.ListObjects("Table1")
        .DataBodyRange.Delete
        .Resize oSheet.Range("A1").Resize(RowCnt, ColCnt)
        oTable.Range.Copy
        .Range.Select
        .Parent.Paste
    End With
    oChart.PlotBy = xlRows
    oChart.ChartData.Workbook.Close
    Application.ScreenUpdating = True
End Sub
© www.soinside.com 2019 - 2024. All rights reserved.