Excel到PDF多个范围

时间:2017-03-14 16:50:33

标签: excel excel-vba pdf presentation vba

这是我当前的代码 - 我不断得到1004运行时错误 - 范围。我有什么想法可以解决这个问题吗?

Sub ToPDF()
'
' Macro2 Macro
'

'
    Sheets("KPIs").Select
    Range("B3:Y46,AA3:AX46,AZ3:BW46,BY3:CV46,CX3:DU46,DW3:ET46,EV3:FS46,B48:Y91,AA48:AX91,AZ48:BW91,BY48:CV91,CX48:DU91,DW48:ET91,EV48:FS91,B93:Y136,AA93:AX136,AZ93:BW136,BY93:CV136,CX93:DU136,DW93:ET136,EV93:FS136,B138:Y181,AA138:AX181,AZ93:BW181,BY138:CV181,CX138:DU181").ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
             "C:\Users\strzelecki-e\Desktop\Macros\KPIs.pdf", Quality:=xlQualityStandard, _
             IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=True

End Sub

1 个答案:

答案 0 :(得分:0)

Sheets("KPIs").Select更改为Sheets("KPIs").Activate。特别是对于较新版本的Excel .Select,据报道会产生错误。

Range("B3:Y46,AA3:AX46,AZ3:BW46,BY3:CV46,CX3:DU46,DW3:ET46,EV3:FS46,B48:Y91,AA48:AX91,AZ48:BW91,BY48:CV91,CX48:DU91,DW48:ET91,EV48:FS91,B93:Y136,AA93:AX136,AZ93:BW136,BY93:CV136,CX93:DU136,DW93:ET136,EV93:FS136,B138:Y181,AA138:AX181,AZ93:BW181,BY138:CV181,CX138:DU181")

太长了。引号之间似乎有255个字符的限制,并且(目前)有260个字符。如果只删除最后一个部分,从而将其缩短为255个字符,那么它将起作用。

或者您也可以执行以下操作:

Dim r As Range

ThisWorkbook.Worksheets("KPIs").Activate

Set r = ThisWorkbook.Worksheets("KPIs").Range("B3:Y46,AA3:AX46,AZ3:BW46,BY3:CV46,CX3:DU46,DW3:ET46,EV3:FS46,B48:Y91,AA48:AX91")
Set r = Union(r, ThisWorkbook.Worksheets("KPIs").Range("AZ48:BW91,BY48:CV91,CX48:DU91,DW48:ET91,EV48:FS91,B93:Y136,AA93:AX136,AZ93:BW136,BY93:CV136,CX93:DU136,DW93:ET136,EV93:FS136"))
Set r = Union(r, ThisWorkbook.Worksheets("KPIs").Range("B138:Y181,AA138:AX181,AZ93:BW181,BY138:CV181,CX138:DU181"))
r.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
    "C:\tmp\KPIs.pdf", Quality:=xlQualityStandard, _
    IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=True

基本上,我只是将范围分成几个较短的位,并add将它们与union一起分割到您要求的最终范围。