Excel图表:使用用户输入到SeriesCollection中

时间:2014-10-16 14:59:47

标签: excel vba

我正在做一个程序,用户将输入他们想要的工作表的名称。之后,程序将创建一个新工作表和新图表,其中包含用户提供的名称。代码如下所示:

Option Explicit

Dim NewWB As Workbook
Dim thisWB As Workbook
Dim i As Integer
Dim test_num As Variant
'Dim sheetName As Variant

Sub NewWSName()

test_num = InputBox("Enter the test number: (Ex: T1 for Test #1)", "Test Number")
If test_num <> "" Then
   Sheets.Add.Name = test_num & " Data"
End If

End Sub

Sub NewChart()

If test_num <> "" Then
   Charts.Add.Name = test_num & " Basic Chart"
End If
End Sub

Sub basic_10()
'Add chart sheet and clear the content
NewChart
ActiveChart.ChartArea.Clear

'Set the chart type as 3D Column
ActiveChart.ChartType = xl3DColumn

Set thisWB = ThisWorkbook
Set NewWB = ActiveWorkbook

With NewWB
    thisWB.Sheets("Basic Chart").ChartArea.Copy
    NewWB.Sheets(ActiveSheet.Name).Paste

    'NewWB.Charts(test_num & " Basic Chart").Activate
    'ActiveChart.ChartArea.Select
    'Here is the error start
    ActiveChart.SeriesCollection(1).Name "=' & test_num & ' Data'!$Q$12"
    ActiveChart.SeriesCollection(1).Values = "=' & test_num & ' Data'!$Q$13:$Q$44"
    ActiveChart.SeriesCollection(2).Name = "=' & test_num & ' Data'!$R$12"
    ActiveChart.SeriesCollection(2).Values = "='" & test_num & " Data!$R$13:$R$44"

End With
End Sub

ActiveChart.SeriesCollection(1).Name "=' & test_num & ' Data'!$Q$12"是我收到错误的地方。如何使用用户输入来指定我希望收集数据的位置?我已经尝试了其他的东西,但也没有用。我无法将其指定为Sheets(1)或类似内容,因为我无法预测用户想要收集数据的次数。有一个更好的方法吗?谢谢你的帮助。

1 个答案:

答案 0 :(得分:0)

尝试在您的Sub中添加此代码代替Sheets.Add.Name = test_num & " Data"

Dim w As Worksheet

Set w = Sheets.Add

w.Name = test_num & " Data"  

您还需要为Charts.Add.Name做类似的事情。