Excel VBA:部分代码仅在单步执行时运行。从其他子程序调用或继续时不运行

时间:2017-11-10 19:20:17

标签: excel-vba vba excel

我正在为我的办公室编写一个格式化Excel加载项的图表。 为了处理嵌入式图表和图表,我在第一个子程序中编写了两个循环。每次激活图表时,都会调用第二个子例程来处理ActiveChart格式化。

我的部分目标是将数据标签应用于折线图,但是即使我设置了DataLabel.ShowSeriesName = True,我的代码也会生成空白数据标签,如图1所示。有两种情况下正确添加标签,如下所述。

Option Explicit

Sub CESAR_style ()
Dim a as application
Dim wb As Workbook
Dim ws As Worksheet
Dim chtO As ChartObject
Dim cht As Chart

Set twb = ThisWorkbook
Set a = Application

' Turn off events
a.EnableEvents = False

' Loop through all chart sheets
For Each cht In a.Charts
  cht.Activate
  Call Format
Next

' Loop through all chart objects
For Each ws In ActiveWorkbook.Worksheets
  For Each chtO In ws.ChartObjects
    chtO.Activate
    Call Format
  Next
Next

a.EnableEvents = True
End Sub
Private Sub Format()
Dim i As Integer
Dim j As Integer

With ActiveChart
    ' Count the series in the chart
    i = .SeriesCollection.Count

    ' Code here to add a new series used to make a 'Today' _
      reference line dividing history and future

    ' Add series data labels, excluding the new series added above
    ' For each data series
    For j = 1 To i
        With .FullSeriesCollection(j)
            ' For Line charts
            If .ChartType = xlLine Then
                ' Turn off leader lines for full series
                .HasLeaderLines = False

            ' Add series data label to right of last point in series
                With .Points(.Points.Count)
                    ' If a label already exists remove it
                    If .HasDataLabel = True Then
                       .HasDataLabel = False
                    Else
                    End If

此代码正常运行,但当.ApplyDataLabels运行时,会创建空白数据标签,如图1所示[空白数据标签] 1

                    ' Add a series data label
                    .ApplyDataLabels ShowSeriesName:=True, _
                            ShowValue:=False, _
                            HasLeaderLines:=False
                End With

            Else
            ' Code here to handle stacked area charts; working properly
            End If
        End With
    Next
End With
End Sub

我在.ApplyDataLabels添加了一个断点。如果我用F5或播放按钮继续代码,它会继续给我空白标签。但是,如果我使用F8或Step Into执行代码,代码会成功执行,我会得到我想要的标签,如图2所示。 Correct data labels

第二个令人困惑的质量是当我将.ApplyDataLabels段移动到CESAR_style子例程时,代码成功运行。

我尝试使用sleep延迟代码,但没有成功。

在我如何设置这两个子程序时,我是否做错了什么?

非常感谢任何帮助或见解。如果需要其他信息来解决问题,请告诉我。

1 个答案:

答案 0 :(得分:0)

一般情况下,对于VBA,我发现如果某些内容在您通过它时有效,而不是在您运行它时,则会出现选择/焦点问题。当您逐步执行代码时,您可能会选择图表所在的工作表,这样您就可以看到代码正在做什么,这有效地为您的宏做了一步。在激活图表之前,尝试激活图表所在的工作表。如果这不起作用,请尝试在工作表上选择一个单元格。

相关问题