[使用MS Word(在我的情况下为2010版本),我构造了一个表单,其中包含要由用户填写的内容控制元素。现在,我希望某些条目(已经赋予标题的条目)显示在同一Word文档中的图表中(而不是在单独的Excel文档中)。
这应该是一个自动化的过程,因此,如果用户更改了内容控制条目之一,则图表将自动更新;如果用户必须按下按钮来更新图表,我也可以(但用户不必单击很多,因为我必须假设用户几乎没有技能。)
因此,我在Word表单文档中插入了一个Excel图表对象。我还在此Excel对象内编写了一些VBA代码,以从Word文档中读取内容控件的值作为图表的源。但是我认为我真正需要的是VBA代码位于我的Word文档本身中(例如,在用户单击按钮时执行),但是我不知道如何处理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图表。
请注意,图表Shapes([indexValue])
的名称(Shape
)可能与此代码不同。您需要检查并更改该分配。另外,您的图表可能是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