使用VBA宏

时间:2017-06-19 21:40:05

标签: excel vba excel-vba ms-office

我在Excel中有一个包含多个页面的工作表。我想打印选定的页面,例如。第1页,第3页,第4页和第6页。我可以在单独的打印作业中执行此操作吗?

知道我可以用命令打印页面: ActiveSheet.PrintOut From:=1, To:=1, Copies:=1, Collate:=True ActiveSheet.PrintOut From:=1, To:=3, Copies:=3, Collate:=True ActiveSheet.PrintOut From:=1, To:=4, Copies:=4, Collate:=True ActiveSheet.PrintOut From:=1, To:=6, Copies:=6, Collate:=True

但是这样,我创造了很多打印作业。所以我看起来像 PrintOut(第1页,第3页,第4页,......)

有关我的问题的更多信息: 我的工作表中有一个发送说明:Excel delivery notes 其中一些在C列中没有条目。 (例如第2页)。我写了一个Makro,它遍历分页符并检查每一页上的C列:

Option Explicit
Sub LieferscheineDrucken()
Dim HPB As HPageBreak
Dim breakAdress As Integer
Dim pageNumber As Integer
Dim productNumber As Integer
Dim printCondition As Boolean
pageNumber = 1
printCondition = False

'Drucke Seite 1
For productNumber = 10 To 61
    ActiveSheet.Cells(productNumber, "C").Select
    If ActiveSheet.Cells(productNumber, "C").Value <> "" Then
    printCondition = True
    End If
Next

If printCondition = True Then
    ActiveSheet.PrintOut From:=1, To:=1, Copies:=1, Collate:=True
End If
printCondition = False
pageNumber = pageNumber + 1


'Drucken der restlichen Seiten
For Each HPB In ActiveSheet.HPageBreaks
    breakAdress = CInt(Mid(HPB.Location.Address, 4, 5))


    'Teste, ob Lieferschein Einträge enthält
     For productNumber = (breakAdress + 9) To (breakAdress + 60)
           If ActiveSheet.Cells(productNumber, "C").Value <> "" Then
                printCondition = True
           End If
     Next

    If printCondition = True Then
        ActiveSheet.PrintOut From:=pageNumber, To:=pageNumber, Copies:=1, Collate:=True
    End If

    pageNumber = pageNumber + 1
    printCondition = False

Next
End Sub

但是这个宏为每个页面发送了一个printjob。如何通过仅发送一个printjob来打印相关页面?

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

代码就是这样。

Sub test()
    Dim Ws As Worksheet
    Dim hp As HPageBreak
    Dim vAddress()
    Dim i As Long

    Set Ws = ActiveSheet
    n = Ws.HPageBreaks.Count

    For i = 0 To n
        ReDim Preserve vAddress(i)
        If i = 0 Then
        vAddress(i) = Ws.Range("a1").Address
        Else
        vAddress(i) = Ws.HPageBreaks(i).Location.Address
        End If
            Set rngDB = Ws.Range(vAddress(i)).Range("c5").Resize(21) 'Range("c5").Resize (21) is coumn C date range
            If WorksheetFunction.CountA(rngDB) Then
                Ws.PrintOut from:=i + 1, To:=i + 1, preview:=True
            End If
    Next i

End Sub