我有一个包含多个工作表的Excel工作簿。对于每个工作表,我想基于指定的数据范围生成图表。图表数据的列将始终相同,但某些工作表将包含比其他工作表更多的数据行。当我只有一个工作表时,我现在的代码似乎工作得很好,但是当我有几个工作表时,它并不总是选择正确的数据范围。我是VBA的新手,所以任何帮助和建议都将不胜感激。提前致谢!
Dim Wb As Workbook
Dim Ws As Worksheet
Dim Cht As Chart
Set Wb = Workbooks.Open(Filename:=Application.GetOpenFilename)
For Each Ws In Wb.Worksheets
Dim MyRange1 As String
Dim MyRange2 As String
Dim MyRange3 As String
Dim MyRange4 As String
MyRange1 = Range([O1], [O1].End(xlDown)).Address
MyRange2 = Range([Q1], [Q1].End(xlDown)).Address
MyRange3 = Range([R1], [R1].End(xlDown)).Address
MyRange4 = Range([S1], [S1].End(xlDown)).Address
MyString1 = MyRange1 & "," & MyRange2
MyString2 = MyRange3 & "," & MyRange4
MyChtRange = MyString1 & "," & MyString2
Set Cht = Ws.Shapes.AddChart.Chart
Cht.SetSourceData Source:=Ws.Range(MyChtRange)
Cht.ChartType = xlColumnStacked
Next Ws
答案 0 :(得分:1)
之后
For Each Ws In Wb.Worksheets
添加一行
Set Ws = ActiveSheet