首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >有没有一种方法可以在Excel中使用VBA根据列值的变化插入分页符,而不是从标题开始?

有没有一种方法可以在Excel中使用VBA根据列值的变化插入分页符,而不是从标题开始?
EN

Stack Overflow用户
提问于 2020-10-02 08:07:56
回答 1查看 130关注 0票数 0

我已经尝试了下面的两个。这两种方法都工作得很好,只是它会导致页面只包含标题,因为所选列中的值从标题值更改为第一个实际值。

选项1:

代码语言:javascript
运行
复制
    Dim I As Long, J As Long
    J = ws.Cells(Rows.Count, "b").End(xlUp).Row
    For I = J To 2 Step -1
    If Range("b" & I).Value <> Range("b" & I - 1).Value Then
    ActiveSheet.HPageBreaks.Add Before:=Range("b" & I)
    End If
    Next I 

选项2:

代码语言:javascript
运行
复制
    Dim rangeSelection As Range
    Dim cellCurrent As Range

    Set rangeSelection = Application.Selection.Columns(2).Cells
    ActiveSheet.ResetAllPageBreaks

    For Each cellCurrent In rangeSelection
    If (cellCurrent.Row > 2) Then
    If (cellCurrent.Value <> cellCurrent.Offset(-1, 0).Value) Then
    ActiveSheet.Rows(cellCurrent.Row).PageBreak = _
    xlPageBreakManual
    End If
    End If
    Next cellCurrent
EN

回答 1

Stack Overflow用户

发布于 2020-10-02 10:35:15

选项1(假设已经设置了ws )

代码语言:javascript
运行
复制
Dim I As Long, J As Long
J = ws.Cells(ws.Rows.Count, "b").End(xlUp).Row
For I = J To 2 Step -1
    If ws.Range("b" & I).Value <> ws.Range("b" & I - 1).Value Then
        ws.HPageBreaks.Add Before:=ws.Range("b" & I)
    End If
Next I 

选项2(假设ws设置为选项1中的值)

代码语言:javascript
运行
复制
Dim rangeSelection As Range
Dim cellCurrent As Range

Set rangeSelection = ws.Range(ws.Cells(1, 2), ws.Cells(ws.Rows.Count, 2).End(xlUp))
ws.ResetAllPageBreaks

For Each cellCurrent In rangeSelection
    If cellCurrent.Row > 2 Then
        If cellCurrent.Value <> cellCurrent.Offset(-1, 0).Value Then
            ws.Rows(cellCurrent.Row).PageBreak = xlPageBreakManual
        End If
    End If
Next cellCurrent
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64164683

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档