多张纸上的宏

时间:2014-04-07 23:27:48

标签: excel vba excel-vba

我想在多张纸上运行此宏。

Sub Macro()


        With ActiveSheet.PageSetup
        .Zoom = 50
     .Orientation = xlPortrait
              .FitToPagesWide = 1
              .FitToPagesTall = 1000
       For Each cell In Range("D:D")
    If InStr(cell, "We warrant") > 0 Then ActiveSheet.HPageBreaks.Add (ActiveSheet.Rows(cel.Row + 1))
           Next
           End With
       End Sub

2 个答案:

答案 0 :(得分:1)

下面的代码遍历每张表。

Sub Macro()
    Dim sht As Worksheet
    For Each sht In ThisWorkbook.Sheets

        With sht.PageSetup
            .Zoom = 50
            .Orientation = xlPortrait
            .FitToPagesWide = 1
            .FitToPagesTall = 1000
            For Each cell In Range("D:D")
                If InStr(cell, "We warrant") > 0 Then sht.HPageBreaks.Add (sht.Rows(cel.Row + 1))
            Next
        End With
    Next
End Sub

此外,您可以使用下面的代码来循环浏览column D中的所有单元格,以获得更好的效果。

 last_row = sht.Range("D" & Rows.Count).End(xlUp).Row
            Set rng = sht.Range("D1:D" & last_row)

            For Each cell In rng
                If InStr(cell, "We warrant") > 0 Then sht.HPageBreaks.Add (sht.Rows(cel.Row + 1))
            Next

答案 1 :(得分:0)

这将满足您的要求:

Sub Macro()
    Dim sht As Worksheet

    'Uncomment whichever you want, the first one will run on the named sheets only, the second will run on all sheets in the workbook

'        For Each sht In Sheets(Array("Hello", "World", "Beans"))
'        For Each sht In Worksheets
        With sht.PageSetup
            .Zoom = 50
            .Orientation = xlPortrait
            .FitToPagesWide = 1
            .FitToPagesTall = 1000
            For Each cell In sht.Range("D1:D" & sht.Range("D" & Rows.Count).End(xlUp).Row)
                If InStr(cell, "We warrant") > 0 Then sht.HPageBreaks.Add (sht.Rows(cel.Row + 1))
            Next
        End With
    Next
End Sub