0

我正在尝试创建我的第一个 VBA 代码,基本上是: - 选择一个单元格 - 按 AZ 对列进行排序 - 透视数据 - 创建一个折线图 - 重新调整图表大小以使其更大

我收到一条运行时错误 9 消息subscript out of range,它突出显示以下行
ActiveWorkbook.Worksheets("advertiserConversionReport_3045").Sort.SortFields。_ 清除

我所做的是打开另一个工作簿并尝试在数据上运行宏。查看代码(我不是开发人员)我看到错误可能是对初始工作簿的引用,advertiserConversionReport_3045也可能是先前设置的枢轴范围Range("A2:F97")

Sub ActionReport()
'
' ActionReport Macro
' This macro will pivot data from the action report and create a line chart to show     trending of credited conversions by day.
'
' Keyboard Shortcut: Ctrl+shift+a
'
Range("B1").Select
ActiveWorkbook.Worksheets("advertiserConversionReport_3045").Sort.SortFields. _
    Clear
ActiveWorkbook.Worksheets("advertiserConversionReport_3045").Sort.SortFields. _
    Add Key:=Range("B1"), SortOn:=xlSortOnValues, Order:=xlAscending, _
    DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets("advertiserConversionReport_3045").Sort
    .SetRange Range("A2:F97")
    .Header = xlNo
    .MatchCase = False
    .Orientation = xlTopToBottom
    .SortMethod = xlPinYin
    .Apply
End With
Sheets.Add
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
    "advertiserConversionReport_3045!R1C1:R97C6", Version:=xlPivotTableVersion14) _
    .CreatePivotTable TableDestination:="Sheet1!R3C1", TableName:="PivotTable1" _
    , DefaultVersion:=xlPivotTableVersion14
Sheets("Sheet1").Select
Cells(3, 1).Select
With ActiveSheet.PivotTables("PivotTable1").PivotFields("Day")
    .Orientation = xlRowField
    .Position = 1
End With
With ActiveSheet.PivotTables("PivotTable1").PivotFields("Conversion Action")
    .Orientation = xlRowField
    .Position = 2
End With
ActiveSheet.PivotTables("PivotTable1").AddDataField ActiveSheet.PivotTables( _
    "PivotTable1").PivotFields("Credited Conversions"), _
    "Sum of Credited Conversions", xlSum
With ActiveSheet.PivotTables("PivotTable1").PivotFields("Conversion Action")
    .Orientation = xlColumnField
    .Position = 1
End With
ActiveSheet.Shapes.AddChart.Select
ActiveChart.ChartType = xlLineMarkers
ActiveChart.SetSourceData Source:=Range("Sheet1!$A$3:$R$11")
ActiveWorkbook.ShowPivotTableFieldList = False
ActiveSheet.Shapes("Chart 1").ScaleWidth 1.6583333333, msoFalse, _
    msoScaleFromTopLeft
ActiveSheet.Shapes("Chart 1").ScaleHeight 1.7065974045, msoFalse, _
    msoScaleFromTopLeft
ActiveWindow.SmallScroll Down:=-24
ActiveSheet.Shapes("Chart 1").IncrementLeft -38.25
ActiveSheet.Shapes("Chart 1").IncrementTop -81.75
End Sub`

有谁知道如何解决这个问题并成功执行宏?

4

1 回答 1

1

您收到该错误是因为“Activeworkbook”没有名为“advertiserConversionReport_3045”的工作表。

避免使用 ActiveWorkbook。创建对象,然后使用它们。您可能想查看此链接

尝试这样的事情

Sub Sample()
    Dim thiswb As Workbook, wbNew As Workbook

    Set thiswb = ThisWorkbook

    '~~> Change as applicable
    Set wbNew = Workbooks.Open("C:\Sample.xlsm")

    With wbNew
        .Worksheets("advertiserConversionReport_3045").Sort.SortFields.Clear
    End With
End Sub
于 2013-09-11T06:10:07.270 回答