【问题标题】:Use Word Content Control Values for chart object in same Word doc对同一 Word 文档中的图表对象使用 Word 内容控制值
【发布时间】:2020-04-16 08:44:55
【问题描述】:

使用 MS Word(在我的例子中是 2010 版),我构建了一个包含内容控制元素的表单,供用户填写。现在,我希望将某些条目(我已经给出标题)显示在同一个 Word 文档(而不是单独的 Excel 文档)内的图表中。

这应该是一个自动化的过程,因此如果用户更改了内容控制条目之一,图表会自动更新;如果用户必须按下一个按钮来更新图表,我也可以(但用户不应该经常点击,因为我必须假设用户没有什么技能。)

所以我在我的 Word 表单文档中插入了一个 Excel 图表对象。我还在这个 Excel 对象中编写了一些 VBA 代码,以从 Word 文档中读取内容控件值作为图表的源。但我认为我真正需要的是在我的 Word 文档本身中的 VBA 代码(例如在用户单击按钮时执行),但我不知道如何处理 Excel 图表对象和单元格内。

我在 Excel 对象中的 VBA 代码是:

Sub ChartDataAcquirer()

Dim wdApp As Object
Dim wdDoc As Object
Dim DocName As String
Dim ccX As String
Dim ccY As String
Dim datapairs As Integer

'''''''''' Variables '''''''''
DocName = "wordform.docm"
ccX = "titleX"
ccY = "titleY"
datapairs = 5
''''''''''''''''''''''''''''''

Set wdApp = GetObject(, "Word.Application")
Set wdDoc = wdApp.Documents(DocName)

Dim i As Integer
For i = 1 To datapairs

    With ActiveSheet.Cells(i + 1, 1) ' The first row contains headline, therefore i+1
    .Value = wdDoc.SelectContentControlsByTitle(ccX & i).Item(1).Range.Text    ' The CC objects containing the x values have titles "titleX1", "titleX2" ..., therefore "ccX & i"
    On Error Resume Next
    .Value = CSng(wdDoc.SelectContentControlsByTitle(ccX & i).Item(1).Range.Text) ' To transform text into numbers, if user filled the CC object with numbers (which he should do)
    End With

    With ActiveSheet.Cells(i + 1, 2)
    .Value = wdDoc.SelectContentControlsByTitle(ccY & i).Item(1).Range.Text
    On Error Resume Next
    .Value = CSng(wdDoc.SelectContentControlsByTitle(ccY & i).Item(1).Range.Text)
    End With

Next

End Sub

我想我需要一个类似的代码,它被放置在 Word 表单文档本身中并在其中运行,但这就是我卡住的地方......

【问题讨论】:

标签: excel vba charts ms-word contentcontrol


【解决方案1】:

以下是演示代码,展示了如何访问嵌入的 Excel 图表。

请注意,图表 Shape 的名称 (Shapes([indexValue])) 可能与此代码中的不同。您需要检查并更改该分配。此外,您的图表可能是InlineShape 而不是Shape,因此您可能还需要调整该位。

此代码检查Shape 是否实际上是一个图表。如果是,则访问Chart 对象及其数据表。通过它,可以获得实际的工作簿、工作表,甚至是 Excel 应用程序(如果需要)。

Sub EditChartData()
    Dim doc As Word.Document
    Dim shp As Word.Shape
    Dim cht As Word.Chart
    Dim wb As Excel.Workbook, ws As Excel.Worksheet, xlApp As Excel.Application

    Set doc = ActiveDocument
    Set shp = doc.Shapes("MyChart")
    If shp.HasChart Then
        Set cht = shp.Chart
        cht.ChartData.Activate
        Set wb = cht.ChartData.Workbook
        Set xlApp = wb.Application
        Set ws = wb.ActiveSheet
        Debug.Print ws.Cells(1, 2).Value2
    End If
    Set ws = Nothing
    Set wb = Nothing
    Set cht = Nothing
    Set xlApp = Nothing
End Sub

【讨论】:

    猜你喜欢
    • 2019-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多