我希望能够在VBA表单中嵌入图表控件,允许用户点击控件的某些部分,这将使用X& D的数据填充隐藏的电子表格。单击Y值。
我使用附加控件机制添加“Microsoft Office Chat 11.0”和“Microsoft Office Spreadsheet 11.0”控件,并将其中一个放在表单上。但是,对于我的生活,我似乎无法将图表绑定到电子表格中包含的数据。我考虑的一个选择是
Dim SpdShtCtr As Spreadsheet
Dim ChartControl As ChChart
Dim XValues() As Variant, YValues() As Variant
XValues = WorksheetFunction.Transpose(SpdShtCtrl.Range("XValues"))
YValues = WorksheetFunction.Transpose(SpdShtCtrl.Range("YValues"))
Dim c
Set c = ChartControl.Constants
With ChartControl
.Clear
.Charts.Add
With .Charts(0).SeriesCollection.Add
.Caption = "Data"
.SetData c.vbDimCategories, c.chDataLiteral, XValues
.SetData c.vbDimValues, c.chDataLiteral, YValues
End With
End With
问题在于它不是动态的 - 如果电子表格中的数据发生变化,图表将不会自动更新。此外,这不起作用。我在.SetData ...
另一种选择是这样的
Dim SpdShtCtr As Spreadsheet
Dim ChartControl As ChChart
Dim XValues As Range, YValues As Range
Set XValues = SpdShtCtrl.Range("XValues")
Set YValues = SpdShtCtrl.Range("YValues")
Dim c
Set c = ChartControl.Constants
With ChartControl
.DataSource = SpdShtCtrl
.Clear
.Charts.Add
With .Charts(0).SeriesCollection.Add
.Caption = "Data"
.SetData c.vbDimCategories, c.chWORKSHEETRANGECONSTANT, XValues
.SetData c.vbDimValues, c.chWORKSHEETRANGECONSTANT, YValues
End With
End With
但是我不知道这是否是将这些控件绑定在一起的正确方法,即使是这样,常量定义应该代替WORKSHEETRANGECONSTANT
来定义到工作表范围的链接
有人能指出我正确的方向吗?
答案 0 :(得分:1)
我将一个ChartSpace(= ChartSpace1)和一个电子表格(= Spreadsheet1)添加到Userform并按照以下方式执行:
Private Sub UserForm_Initialize()
Dim chc As ChChart
With Spreadsheet1
For i = 1 To 3 ' just filling sample Data to Spreadsheet
.Cells(i, 1) = i
.Cells(i, 2) = i + 2
Next
End With
Set chc = ChartSpace1.Charts.Add
chc.Type = chChartTypeScatterSmoothLineMarkers
ChartSpace1.DataSource = Spreadsheet1 ' linking the Spreadsheet and the Chart
chc.SeriesCollection.Add
With chc.SeriesCollection(0)
.SetData chDimSeriesNames, 0
.SetData chDimCategories, 0
.SetData chDimXValues, 0, "A1:A3" ' setting the x coordinate range
.SetData chDimYValues, 0, "B1:B3" ' setting the y coordinate range
End With
chc.HasLegend = True
End Sub
适合我,但我不知道这是否能满足你所需的一切。