【问题标题】:How to fix "compile error: next without for" error in VBA?如何修复 VBA 中的“编译错误:next without for”错误?
【发布时间】:2017-01-02 09:58:11
【问题描述】:

所以我对 VBA 编码或一般编程非常陌生。我收到“编译错误:下一步没有 for”。我相信我会为 3 个 fors 提供 3 个下一个,但我仍然不知道。下面是我正在处理的代码......

Sub width2() '自动分配系列宽度

For Series = 1 To 24  'chart series, 144 combinations
        For i = 0 To 1
                For j = 0 To 11
                    ActiveSheet.ChartObjects("Chart 4").Activate
                    ActiveChart.FullSeriesCollection(Series).Select
                    With Selection.Format.Line
                        .Visible = msoTrue
                        .Weight = Sheet5.Range("Q9").Offset((9 * i) + 6, (3 * j)).Value
                Next j
        Next i
Next Series
End Sub

不确定错误在哪里。 非常感谢任何帮助 谢谢。

【问题讨论】:

  • 你错过了End With 到你的With Selection.Format.Line
  • With 方法可能有问题。你没有关闭With。您必须在Next j 之前使用End With
  • 在下一个 j 之前添加 end with 后,我现在得到:“找不到具有指定名称的项目”,行:ActiveSheet.ChartObjects("Chart 4").Activate
  • 确保您的活动工作表中有一个名为 Chart 4 的图表...
  • @PiyushVerma 请使用 End With 更新您的代码,以便我们从您的帖子中删除该错误。 Secod,您需要将您的ActiveSheet.ChartObjects("Chart 4").Activate 和嵌套For 循环中的以下行作为Sub 的第一行。只需将.Weight = Sheet5.Range("Q9").Offset((9 * i) + 6, (3 * j)).Value 保留在里面

标签: vba excel loops for-loop


【解决方案1】:

由于您没有共享您的工作表数据结构,这不是完整的答案。

代码运行无需使用ActivateActiveChartSelect。相反,它引用“图表 6”ChartObject,然后使用以下With 语句修改SeriesCollectionLine.VisibleLine.Weight 属性:With MyCht.Chart.SeriesCollection(12 * i + j + 1)

注意:如果@Piyush Verma 决定分享他的数据结构,Sheet5.Range("Q9").Offset((9 * i) + 6, (3 * j)).Value 的数学部分也可以处理。

代码

Option Explicit

Sub ChartSer_LineWidth()

Dim i As Long, j As Long
Dim MyCht As ChartObject

' set the chart object of Chart 6 to a variable
Set MyCht = ActiveSheet.ChartObjects("Chart 6")

For i = 0 To 1
    For j = 0 To 11

        With MyCht.Chart.SeriesCollection(12 * i + j + 1)
            .Format.Line.Visible = msoTrue
            .Format.Line.Weight = Sheet5.Range("Q9").Offset((9 * i), (3 * j)).Value
        End With

    Next j
Next i

End Sub

【讨论】:

  • 不客气,请标记为答案(点击我的答案旁边的小V
【解决方案2】:
For Series = 1 To 24  'chart series, 144 combinations
    For i = 0 To 1
            For j = 0 To 11
                ActiveSheet.ChartObjects("Chart 4").Activate
                ActiveChart.FullSeriesCollection(Series).Select
                With Selection.Format.Line
                    .Visible = msoTrue
                    .Weight = Sheet5.Range("Q9").Offset((9 * i) + 6, (3 * j)).Value
                End With
            Next j
    Next i
 Next Series

【讨论】:

    【解决方案3】:

    您必须用“EndWith”关闭每个“With”。这在您的代码中被省略了。

    还要用“EndIf”关闭每个“if”,用“Next”关闭“for”,以避免“编译错误:Next without for”

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-06-30
      • 2015-05-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多