将IfTo语句用于If / Else时出错

时间:2017-04-25 14:26:59

标签: excel-vba loops goto vba excel

仅当相关列中有数据时,我才使用以下代码调整图表元素的外观:

mcwb.ChartObjects("Combined RTS").Activate
k = 3
Dim c1 As Range
Dim c2 As Range

Do Until wb.Worksheets("RTS Raw Data").Cells(1, k) = ""
  Set c1 = Cells(3, k)
  Set c2 = Cells(lr, k)

  With wb.Worksheets("RTS Raw Data")
    If (.Cells(3, k) <> "-999") Then
    ActiveChart.SeriesCollection.Add Source:=.Range(.Cells(3, k), .Cells(lr, k))
        GoTo Line1
    Else
        GoTo Line2
    End If
  End With

Line1:
  ActiveChart.SeriesCollection(11 + k).XValues = wb.Worksheets("RTS Raw Data").Range("B3:B" & lr)
  ActiveChart.SeriesCollection(11 + k).Name = wb.Worksheets("RTS Raw Data").Cells(2, k)
  ActiveChart.SeriesCollection(11 + k).AxisGroup = xlPrimary
Line2:
  If (wb.Worksheets("RTS Raw Data").Cells(3, k) = "-999") Then
    mcwb.Shapes("CheckBox" & 8 + k).TextFrame.Characters.Text = "Unused"
  Else
    mcwb.Shapes("CheckBox" & 8 + k).TextFrame.Characters.Text = wb.Worksheets("RTS Raw Data").Cells(2, k)
  End If

  k = k + 1
Loop

但是,如果运行此标记,则Line1标签中的代码会返回不正确的使用错误。我的目标是减少运行脚本时使用的指令量和循环中花费的时间。提前谢谢。

1 个答案:

答案 0 :(得分:2)

错误正在发生,因为您在GoTo块中使用了With,并且该块正在超出范围。避免With阻止,或避免使用GoTo语句(除非非常特殊的用途,否则通常不赞成)。

使用ChartSeries以及Worksheet对象也可以改善这一点,这会使代码更加清晰:)我们还可以改进if /的嵌套其他条件使用If/ElseIf/Else,您应使用您的变量(例如c1, c2,而不是通过.Cells标识符重复引用它们。)

Dim cht as Chart
Dim srs as Series
Dim wsRTS as Worksheet
Set cht = ActiveChart
Set wsRTS = wb.Worksheets("RTS Raw Data")

With wsRTS
    Do Until .Cells(1, k) = ""
      'If these Cells are on wsRTS, you could put the entire DO LOOP inside the WITH block.
      Set c1 = .Cells(3, k)
      Set c2 = .Cells(lr, k)

      If c1.Value <> "-999" Then
          'Use your c1,c2 range objects to define the series range!
          Set srs = cht.SeriesCollection.Add(Source:=.Range(c1, c2))
          srs.XValues = .Range("B3:B" & lr).Value
          srs.Name = .Cells(2, k)
          srs.AxisGroup = xlPrimary
      ElseIf c1.Value = "-999" Then
          mcwb.Shapes("CheckBox" & 8 + k).TextFrame.Characters.Text = "Unused"
      Else
          mcwb.Shapes("CheckBox" & 8 + k).TextFrame.Characters.Text = .Cells(2, k)
      End If
      k = k + 1
    Loop
End With

如果您在实施上述内容时遇到困难,请从下面的内容开始,并尝试逐个实施某些更改,以便使用上述建议清理代码。例如,您Set c1但从不使用它,即使您在代码中的其他地方引用该对象(.Cells(3,k)),获取Series对象的句柄意味着您可以使用它而不是{ {1}}这是一个笨拙的构造,你使用ActiveChart.SeriesCollection(_index_)但是在With wb.Worksheets("RTS Raw Data")块中明确地重复引用该对象,这违背了使用目的首先是With块!等等:

With