我试图写一个VBScript文件(xxx.vbs),它可以打开.CSV文件,格式化它并绘制数据图表。一切正常,除了一件事 - ActiveChart.ChartTitle的设置。当我在VBA中对其进行原型设计时,它可以正常工作,但是当我从VBScript文件中执行它时,它似乎忽略了它。
以下是我的xxx.vbs文件的基本要素的清理版本:
' Using Excel 2013
Const xlBarClustered = 57, xlLocationAsNewSheet = 1
' Assume for this exercise Excel is already open and on the correct sheet
Set oExcel = GetObject(, "Excel.Application")
Set SheetData = oExcel.ActiveSheet
' Assume Labels in A2:A21, Data in B2:B21 and Title in B1
oExcel.Range("A2:B21").Select
SheetData.Shapes.AddChart2(216, xlBarClustered).Select
Set aChart = oExcel.ActiveChart
With aChart
.Location xlLocationAsNewSheet, "TestChart"
.ChartType = xlBarClustered
.SetSourceData oExcel.Range(SheetData.Name & "!A2:B21")
.HasTitle = True
With .ChartTitle
' I've tried each of these in turn and none set anything
.Text = "=" & SheetData.Name & "!B1"
.Formula = SheetData.Name & "!B1"
.Caption = "=" & SheetData.Name & "!B1"
End With
End With
答案 0 :(得分:0)
我在Excel中创建了一个没有标题的图表,然后运行了这段代码,它对我有用(Excel 2010)。
Const msoElementChartTitleAboveChart = 2
With GetObject(, "Excel.Application")
.ActiveChart.SetElement msoElementChartTitleAboveChart
.ActiveChart.ChartTitle.Text = "Test Title"
End With
答案 1 :(得分:0)
我解决了自己的问题!我开始怀疑代码是否无法正常工作。没有附加到正确的对象。事实证明.Location命令会更改ActiveChart对象。通过重新选择Chart,现在可以正常工作(除了一些额外的常量之外,其他代码如上所述):
SheetData.Shapes.AddChart2(216, xlBarClustered).Select
oExcel.ActiveChart.Location xlLocationAsNewSheet, "TestChart"
Set aChart = oExcel.Charts(1)
With aChart
.HasTitle = True
.ChartTitle.Formula = "=" & SheetData.Name & "!B1"
With .Axes(xlValue)
.MajorUnit = 1
.MinorUnit = 1
.HasTitle = True
.AxisTitle.Caption = "Test"
End With
.Axes(xlCategory).ReversePlotOrder = True
.Axes(xlCategory).Crosses = xlMaximum
End With
我希望它可能对其他人有用!