【问题标题】:How can I Conditionally Insert Rows after Page Breaks in Excel VBA?如何在 Excel VBA 中的分页符后有条件地插入行?
【发布时间】:2018-04-19 21:32:18
【问题描述】:

我目前正在尝试编写一个宏,在适当的时候在每个新页面的顶部插入一个“标题继续”和“字幕继续”行。为此,我想遍历每一行并确定:

  1. 该行是不是标题或副标题的分页符(如果是,一行插入“标题继续”,另一行插入“副标题继续”),
  2. 该行是否是分页符并且已经是副标题(如果是,只插入“标题续”),
  3. 该行是否已经是标题或不是分页符(如果是,请跳过),

目前,除了字幕和标题本身之外的每一行,字幕和标题分别存储在 C 和 D 列中。对于标题和副标题行,C 和 D 列是空白的。我遇到的问题是在第一次插入发生后我变得奇怪。大多数行插入宏都会倒退,但这在这里不起作用,因为在分页符之前插入行之后分页符会发生变化。这是我写的代码:

Inserts = 0
Dim Counter As Long
Counter = 1
While Counter < RowCount
    If Rows(Counter).PageBreak <> -4142 And Cells(Counter, "C").Value <> "" Then
        Range("C" & (Counter), "C" & (Counter + 1)).EntireRow.Insert
        Cells(Counter, "A").Value = UCase(Cells(Counter + 2, "D").Value) & " continued"

        Cells(Counter + 1, "A").Value = UCase(Cells(Counter + 2, "C").Value) & " continued"

        Counter = Counter + 3
        Inserts = Inserts + 2
    ElseIf Rows(Counter).PageBreak <> -4142 And Cells(Counter + 1, "C").Value <> "" Then
        Range("C" & Counter).EntireRow.Insert
            Cells(Counter, "A").Value = UCase(Cells(Counter + 2, "D").Value) & " continued"

        Counter = Counter + 2
        Inserts = Inserts + 1
    Else: Counter = Counter + 1
    End If
Wend
RowCount = RowCount + Inserts - 2

谢谢!

安迪

【问题讨论】:

  • 有人有什么想法或批评吗?

标签: excel loops page-break vba


【解决方案1】:

更新:此代码确实按预期工作。问题是电子表格中的其他列正在影响分页符,即使它们超出了打印范围。我在运行此段后删除了代码中的这些列,因此分页符随后发生了变化,给人的印象是这部分不起作用。将所有自动分页符设置为 xlPageBreakManual 解决了这个问题,而不会强迫我提前删除列(因为我需要它们的数据)。

【讨论】:

    猜你喜欢
    • 2018-10-03
    • 1970-01-01
    • 1970-01-01
    • 2015-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多