我正在尝试使用以下代码创建新图表:
Sheet1.Range("C1:C21").TextToColumns Destination:=Sheet1.Range("C1"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, _
Semicolon:=False, Comma:=False, Space:=False, Other:=False, FieldInfo _
:=Array(1, 1), TrailingMinusNumbers:=True
Sheet1.Select
Set classificacio = Sheet1.Shapes.AddChart2(Style:=-1, XlChartType:=xlBarStacked, Left:=Sheet1.Cells(1, 1).Left, Top:=Sheet1.Cells(1, 1).Top, Width:=Sheet1.Range(Cells(1, 1), Cells(15, 8)).Width, Height:=Sheet1.Range(Cells(1, 1), Cells(20, 8)).Height, NewLayout:=True).Chart
classificacio.SetSourceData Source:=Range(Sheet1.Cells(11, 2), Sheet1.Cells(20, 3))
classificacio.HasTitle = False
有效。但是,当我删除Sheet1.Select
时它不起作用,因为该代码是在Sheet3处于活动状态时启动的。看来Set classificacio = Sheet1.Shapes...
仅在Sheet1是ActiveSheet时才有意义。
如何创建此图表以避免选择创建图表的Sheet1,而始终将Sheet3保留为ActiveSheet?
答案 0 :(得分:1)
您收到该错误,因为Cells对象不完全合格。如果您不符合条件,则它们将引用活动表。
将Sheet1.Range(Cells(1, 1), Cells(15, 8))
更改为Sheet1.Range(Sheet1.Cells(1, 1), Sheet1.Cells(15, 8))
。与Sheet1.Range(Cells(1, 1), Cells(20, 8))
或更妙的是,然后将其放入With-End With
块(未经测试)。
With Sheet1
.Range("C1:C21").TextToColumns Destination:=.Range("C1"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, _
Semicolon:=False, Comma:=False, Space:=False, Other:=False, FieldInfo _
:=Array(1, 1), TrailingMinusNumbers:=True
Set classificacio = .Shapes.AddChart2(Style:=-1, XlChartType:=xlBarStacked, _
Left:=.Cells(1, 1).Left, _
Top:=.Cells(1, 1).Top, _
Width:=.Range(.Cells(1, 1), .Cells(15, 8)).Width, _
Height:=.Range(.Cells(1, 1), .Cells(20, 8)).Height, _
NewLayout:=True).Chart
classificacio.SetSourceData Source:=Range(.Cells(11, 2), .Cells(20, 3))
classificacio.HasTitle = False
End With