【问题标题】:VBA Object variable or With block variable not setVBA 对象变量或未设置块变量
【发布时间】:2020-02-08 09:02:22
【问题描述】:

这段代码的重点是在一个新的工作表中创建一个图表,它确实如此。在此之后,当我单击按钮在一个名为相同的新工作表中再次生成图表时,它应该删除该工作表并创建一个新的生成图表。

它会创建图表,但是当我返回单击按钮时,它会在按钮所在的工作表中生成图表并抛出错误 91:对象变量或未设置块变量。

调试将我指向以下行:

ActiveChart.Location Where:=xlLocationAsNewSheet, Name:="Demand Line Chart"

下面是代码:

Sub HistoricalDemand()
' Creates a line chart for the demand column

For Each ws In Worksheets
         If ws.Name = "Demand Line Chart" Then
                Application.DisplayAlerts = False
                   Sheets("Demand Line Chart").Delete
                Application.DisplayAlerts = True
                Exit For
         End If
        Next

Columns("A:A").Select
Selection.NumberFormat = "[$-en-US]mmm-yy;@"

Range("A:A,E:E").Select
ActiveSheet.Shapes.AddChart2(332, xlLineMarkers).Select
' Try With command here
ActiveChart.SetSourceData Source:=Range("A:A,E:E")
ActiveChart.Location Where:=xlLocationAsNewSheet, Name:="Demand Line Chart"
' Places line chart in a new worksheet called Demand Line Chart
ActiveChart.Axes(xlCategory).Select
Selection.TickLabels.Orientation = 70
Selection.MajorTickMark = xlNone
With ActiveChart
    .Axes(xlCategory).Select
    .Axes(xlCategory).MajorUnit = 2
    .ChartTitle.Select
    .ChartTitle.Text = "Historical Demand"
    .SetElement (msoElementLegendRight)
Selection.Format.TextFrame2.TextRange.Characters.Text = "Historical Demand"
With Selection.Format.TextFrame2.TextRange.Characters(1, 17).ParagraphFormat
    .TextDirection = msoTextDirectionLeftToRight
    .Alignment = msoAlignCenter
End With
ActiveChart.ChartArea.Select
End With
End Sub

【问题讨论】:

  • 图表应该在哪个表(名称)中创建?一张新表?保存图表源数据的工作表的名称是什么?
  • @RicardoDiaz 应该在其中创建图表的工作表名称是一个名为“需求线图”的新工作表。保存图表源数据的工作表的名称称为“DATA”。这是电子表格的图片:imgur.com/a/8WWPxNQ
  • 看到您以前的问题有很好的答案,但没有标记它们。如果他们解决了您的问题,请记住检查每个答案左侧的标记,以便其他人可以找到他们。
  • @RicardoDiaz 完成,感谢您的留言。

标签: excel vba excel-charts


【解决方案1】:

使用 VBA 编码时的一些建议:

  1. 使用option explicit,这样您就不会出现未定义变量的意外行为
  2. 始终缩进您的代码(请参阅www.rubberduckvba.com 一个帮助您处理数据的免费工具)
  3. 尝试将您的逻辑定义变量和重用它们分开
  4. Avoid using select 除非绝对必要

查看和自定义代码,使其符合您的需求。

您可以通过按F8 并逐行执行来查看代码中发生的情况。

代码:

Public Sub HistoricalDemand()
    ' Creates a line chart for the demand column
    Dim targetSheet As Worksheet
    Dim sourceDataSheet As Worksheet
    Dim sourceDataRange As Range
    Dim targetChart As Shape

    Dim targetSheetName As String
    Dim targetChartTitle As String
    Dim dataLastRow  As Long

    ' Define parameters
    targetSheetName = "Demand Line Chart"
    targetChartTitle = "Historical Demand"

    ' Set a reference to the source data sheet
    Set sourceDataSheet = ThisWorkbook.Worksheets("DATA")

    ' Find last row in data sheet
    dataLastRow = sourceDataSheet.Cells(sourceDataSheet.Rows.Count, 1).End(xlUp).Row

    ' Set reference to the source range
    Set sourceDataRange = sourceDataSheet.Range("A1:A" & dataLastRow & ",E1:E" & dataLastRow)

    ' Delete the sheet if exists
    For Each targetSheet In Worksheets
        If targetSheet.Name = targetSheetName Then
            Application.DisplayAlerts = False
            ' This will delete the matching sheet
            targetSheet.Delete
            Application.DisplayAlerts = True
            Exit For
        End If
    Next

    ' Apply format to the first column (A)
    sourceDataSheet.Range("A1:A" & dataLastRow).NumberFormat = "[$-en-US]mmm-yy;@"

    ' Add the chart
    Set targetChart = sourceDataSheet.Shapes.AddChart2(332, xlLineMarkers)

    ' Apply the target chart settings
    With targetChart.Chart
        .SetSourceData Source:=sourceDataRange
        .Location Where:=xlLocationAsNewSheet, Name:=targetSheetName
        ' Places line chart in a new worksheet called Demand Line Chart
        .Axes(xlCategory).TickLabels.Orientation = 70
        .Axes(xlCategory).MajorTickMark = xlNone

        .Axes(xlCategory).Select
        .Axes(xlCategory).MajorUnit = 2

        .ChartTitle.Text = targetChartTitle
        .SetElement (msoElementLegendRight)
        .ChartTitle.Format.TextFrame2.TextRange.Characters.Text = targetChartTitle
        With .ChartTitle.Format.TextFrame2.TextRange.Characters(1, 17).ParagraphFormat
            .TextDirection = msoTextDirectionLeftToRight
            .Alignment = msoAlignCenter
        End With
    End With

End Sub

让我知道它是否有效

【讨论】:

  • 非常感谢您,很明显您在回答我时考虑到了这一点,我对此表示感谢。我似乎仍然无法修复我的代码。我以前没有看到很多你输入的内容,所以就可读性而言,它有点超出我的范围。但是 ruberduckvba 非常好!
  • 记住你可以使用F8来查看代码在做什么。代码在哪一行不起作用,我们可以对其进行调试。我们的想法是让它发挥作用。
  • 好的,现在就这样做。
  • 在调试了几次之后,问题似乎发生在这里: ActiveSheet.Shapes.AddChart2(332, xlLineMarkers).Select 它正在将图表插入到数据工作表中,然后再将其插入到新的工作表中一。删除它时出现错误:对象变量未设置块变量。
  • 是的,使用我的代码并调试它。我所做的是获取您的代码并对其进行重构以应用我提到的建议,但我保留了您的逻辑。当您阅读 cmets 时,会解释这些操作。只需一步到位。使用宏记录的代码会导致您遇到的问题,即活动表不支持添加和选择图表
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多