尝试从宏添加分页时出现错误1004

时间:2017-03-06 19:00:39

标签: excel vba excel-vba

我有一个使用POI创建的电子表格,但每当我尝试使用它设置分页符时,POI会导致一些问题。所以我们只是在每行的第一列设置一个特定的字符串,我们想要一个分页符并使用一个宏来用分页符替换该字符串。但是每当我运行它时,我都会收到错误Run-time error '1004': unable to set the PageBreak property of the Range class

我们正在使用的宏是:

Sub testPrintBreak()
Application.ScreenUpdating = False
    For i = 2 To ActiveSheet.UsedRange.Rows.Count
        If Cells(i, 1).Value = "EMY-REPLACE WITH PAGE BREAK-EMY" Then
            Cells(i, 1).PageBreak = xlPageBreakManual
        End If
    Next
Application.ScreenUpdating = True
End Sub

我们还尝试了另一个:

Sub InsertPageBreaksByKeyphrase()
    Dim rangeSelection As Range
    Dim cellCurrent As Range

    Set rangeSelection = Application.Selection
    ActiveSheet.ResetAllPageBreaks

    For Each cellCurrent In rangeSelection
        If cellCurrent.Value = "EMY-REPLACE WITH PAGE BREAK-EMY" Then
            ActiveSheet.Rows(cellCurrent.Row + 1).PageBreak = _
                xlPageBreakManual
        End If
    Next cellCurrent
End Sub

出了同样的错误。我在这里不知所措,我无法弄清楚造成它的原因。

编辑:如果你投票结果留下评论,为什么你没有完全没用,谢谢。

1 个答案:

答案 0 :(得分:0)

我认为这是因为你不会添加它。

试试这个:

Sub testPrintBreak()
Application.ScreenUpdating = False
    For i = 2 To ActiveSheet.UsedRange.Rows.Count
        If Cells(i, 1).Value = "EMY-REPLACE WITH PAGE BREAK-EMY" Then
            ActiveSheet.HPageBreaks.Add Before:=Cells(i, 1)
         End If
    Next
Application.ScreenUpdating = True
End Sub

编辑:这只是为了好奇,这有用吗?

Sub testPrintBreak()
Dim ws as Worksheet
Set ws = ActiveSheet
Application.ScreenUpdating = False
    For i = 2 To ws.UsedRange.Rows.Count
        If ws.Cells(i, 1).Value = "EMY-REPLACE WITH PAGE BREAK-EMY" Then
            ws.Cells(i, 1).PageBreak = xlPageBreakManual
        End If
    Next
Application.ScreenUpdating = True
End Sub