如何在当前表单中将macros指向单元格范围?

我录制了一个macros在工作表上创buildgraphics。 数据在工作簿的所有表格中都以相同的方式组织,因此我想概括一下macros,以便可以在每个工作表上使用它(或者可以通过工作表进行批处理)。

代码如下所示:

ActiveWindow.SmallScroll Down:=-57 Range("C5:C65").Select ActiveSheet.Shapes.AddChart.Select ActiveChart.ChartType = xlLine ActiveChart.SetSourceData Source:=Range("fr_1!$C$5:$C$65") ActiveChart.Axes(xlCategory).Select ActiveChart.SeriesCollection(1).XValues = "=fr_1!$A$5:$A$65" 

在fr_1上logging了这个macros之后,我现在在第五行和最后一行中提到了这个参考,而我希望对活动工作表有一个总体的参考。

我该怎么做呢?

您可以:

 Dim aSheet As Worksheet For Each aSheet In ActiveWorkbook.Worksheets With aSheet.Shapes.AddChart.Chart .ChartType = xlLine .SetSourceData Source:=aSheet.Range(aSheet.Name & "!$C$5:$C$65") .SeriesCollection(1).XValues = "=" & aSheet.Name & "!$A$5:$A$65" End With Next 

如果要迭代手动select的工作表,请更改for each asheet in activewindow.selectedsheets

按名称手动过滤;

 Dim aSheet As Worksheet For Each aSheet In ActiveWorkbook.Worksheets select case aSheet.name case "sheet1", "sheet50", "sheet999" With aSheet.Shapes.AddChart.Chart .ChartType = xlLine .SetSourceData Source:=aSheet.Range(aSheet.Name & "!$C$5:$C$65") .SeriesCollection(1).XValues = "=" & aSheet.Name & "!$A$5:$A$65" End With end select Next 

您可以

  • 将所需的图纸添加到数组,然后访问要放置图表的工作表。 此代码仅在由Arrshts = Array("Sheet1", "Sheet3", "MySheet With Space")提供的三个表名称上运行
  • 通过仅引用本地范围来跳过潜在的命名问题

[已更新 – 为潜在的无效表名添加error handling]

  Sub Sample() Dim ws As Worksheet Dim Arrshts() Dim ArrSht Dim strOut As String Arrshts = Array("Sheet1", "Sheet3", "MySheet With Space") For Each ArrSht In Arrshts On Error Resume Next Set ws = Nothing Set ws = Sheets(ArrSht) On Error GoTo 0 If Not ws Is Nothing Then With Sheets(ArrSht).Shapes.AddChart.Chart .ChartType = xlLine .SetSourceData Range("$C$5:$C$65") .SeriesCollection(1).XValues = Range("$A$5:$A$65") End With Else strOut = strOut & (vbNewLine & ArrSht) End If Next If Len(strOut) > 0 Then MsgBox strOut, , "These array names are incorrect and need adjusting" End Sub