Excel VBA跨工作表添加图表数据系列遇1004错误求助
解决VBA跨工作表设置图表数据系列的运行时错误'1004'
错误根源
你的代码里Sheets(data_sheet).Range(Cells(...), Cells(...))存在一个隐性问题:Cells没有指定所属工作表,默认会引用当前活动工作表的单元格。当data_sheet不是活动表时,Range属于目标数据工作表,但Cells指向的是当前激活的工作表,二者所属对象不匹配,直接触发1004错误。
而test_range2 = Sheets(data_sheet).Range("CH32:CH55")能正常运行,是因为它直接使用了完整的单元格地址,没有依赖未指定父对象的Cells。
修复后的代码(无需激活工作表)
给Cells加上对应的父工作表引用,就能直接用一行代码完成赋值,不用再激活目标工作表:
For dataset = 2 To num_datasets next_series_startrow = end_1stdata_row + 3 next_series_endrow = next_series_startrow + (end_1stdata_row - start_1stdata_col) ActiveChart.SeriesCollection.NewSeries ActiveChart.SeriesCollection(dataset).Values = Sheets(data_sheet).Range( _ Sheets(data_sheet).Cells(next_series_startrow, start_1stdata_col), _ Sheets(data_sheet).Cells(next_series_endrow, start_1stdata_col) _ ) ActiveChart.SeriesCollection(dataset).Name = series_name(dataset) Next
更简洁的写法(推荐)
提前定义数据工作表对象,减少重复代码,可读性更强:
Dim wsData As Worksheet Set wsData = Sheets(data_sheet) For dataset = 2 To num_datasets next_series_startrow = end_1stdata_row + 3 next_series_endrow = next_series_startrow + (end_1stdata_row - start_1stdata_col) ActiveChart.SeriesCollection.NewSeries With ActiveChart.SeriesCollection(dataset) .Values = wsData.Range(wsData.Cells(next_series_startrow, start_1stdata_col), _ wsData.Cells(next_series_endrow, start_1stdata_col)) .Name = series_name(dataset) End With Next
内容的提问来源于stack exchange,提问作者MightyMouseZ
相关产品推荐
相关产品推荐

