Excel VBA在PDF的单独页面中打印多个命名范围

时间:2016-10-05 08:51:42

标签: excel vba dynamic range named

我有命名范围的列表,我设置的每个范围都适合单页。我使用以下代码导出到PDF中,它被合并到单页中。

Dim wbBook As Workbook
Dim i As Integer
Dim rs As Range

Set wbBook = ActiveWorkbook
Set rs = wbBook.Names(1).RefersToRange
For i = 2 To wbBook.Names.Count
   Set rs = Union(rs, wbBook.Names(i).RefersToRange)
Next

rs.ExportAsFixedFormat xlTypePDF, strPath, , , False

但是,当我手动输入范围名称时,以下代码适用于我。而我的命名范围是动态的。我认为,上面的代码需要一些修改才能工作。有人会协助我完成这件事吗?

Set rs = wbBook.Range("Page_1,Page_2,Page_3")
rs.Select
Selection.ExportAsFixedFormat xlTypePDF, strPath, , , False

建议的解决方案仍然给出一页。我在页面设置下方提供,页面设置有问题吗?

With Sheet1.PageSetup
.PrintArea = Range(Cells(iBeginRow, 1), Cells(iRow + 2, 5)).Address
.CenterHorizontally = True
.CenterVertically = True
.Orientation = xlLandscape
.LeftMargin = Application.InchesToPoints(0)
.RightMargin = Application.InchesToPoints(0)
.TopMargin = Application.InchesToPoints(0)
.BottomMargin = Application.InchesToPoints(0)
.HeaderMargin = Application.InchesToPoints(0)
.FooterMargin = Application.InchesToPoints(0)
.PrintQuality = 600
.FitToPagesWide = 1
.FitToPagesTall = 1
End With

然后我动态命名范围

Sheet1.Range(Cells(iBeginRow, 1), Cells(iRow + 2, 5)).Select
Selection.Name = "Page_" & PageNum

1 个答案:

答案 0 :(得分:1)

UDF下面为我工作(我在模块中有它):

Sub ExportRangeToPDF(ByVal WSName As String)

    Dim oRng As Range
    Dim strPath As String: strPath = "C:\temp\Temp\"
    Dim intCount As Integer

    For intCount = 1 To ActiveWorkbook.Names.Count

        If InStr(1, LCase(ActiveWorkbook.Names(intCount).RefersToRange.Name.Name), LCase(WSName)) > 0 Then

            If oRng Is Nothing Then
                Set oRng = Range(ActiveWorkbook.Names(intCount).RefersToRange.Name.Name)
            Else
                Set oRng = Union(oRng, Range(ActiveWorkbook.Names(intCount).RefersToRange.Name.Name))
            End If

        End If

    Next

    oRng.ExportAsFixedFormat xlTypePDF, strPath & "test.pdf", , , False

    Set oRng = Nothing

End Sub

注意:我有一些解决方案'和' filterdatabase'我正在处理的工作簿中的范围,因此必须在工作之前添加一些验证。如果您的工作簿中有任何此类范围,则可能必须执行相同的