使用VBA将范围添加到现有的PrintArea失败,错误400

我试图扩展我的Excel工作表的当前打印区域,但目前,使用下面的代码。 它打破了第三个.PageSetup.PrintArea ,我不知道为什么。

代码:

 With ActiveSheet .PageSetup.PrintArea = "$A$1:$A$5" MsgBox (.PageSetup.PrintArea & "," & .Cells(8, 1).Address & ":" & .Cells(10, 1).Address) .PageSetup.PrintArea = .PageSetup.PrintArea & "," & .Cells(8, 1).Address & ":" & .Cells(10, 1).Address MsgBox (.PageSetup.PrintArea & "," & .Cells(15, 1).Address & ":" & .Cells(20, 1).Address) .PageSetup.PrintArea = .PageSetup.PrintArea & "," & .Cells(15, 1).Address & ":" & .Cells(20, 1).Address End With 

在最后一行,它使我“错误400”,我不知道为什么,这是完全一样的线路上面。 我也试过; 而不是,但它不知道。 如果您有任何想法,请告诉我,我会很高兴听到它。 谢谢,Clément

我希望你的Windows设置为使用不是逗号的列表分隔符。 在我的情况下,printarea属性在第二行代码(注意分号)后返回:

 $A$1:$A$5;$A$8:$A$10 

但为了设置这个打印区域, 必须用逗号replace:

 ActiveSheet.PageSetup.PrintArea = "$A$1:$A$5,$A$8:$A$10" 

所以,在我的系统中,为了使您的代码正常工作,我需要使用:

 .PageSetup.PrintArea = Replace(.PageSetup.PrintArea, ";", ",") & "," & .Cells(15, 1).Address & ":" & .Cells(20, 1).Address 

使用.Union ( Application.Union方法 ):

 .PageSetup.PrintArea = Union(.Range("$A$1:$A$5"), .Range(.Cells(8, 1), .Cells(10, 1)), .Range(.Cells(15, 1), .Cells(20, 1))).Address 

join所有3个范围。


或者使用

 .PageSetup.PrintArea = Union(.Range("Print_Area"), .Range(.Cells(8, 1), .Cells(10, 1))).Address 

将范围添加到现有的打印区域。
这里我们使用现有的打印区域被保存为命名范围Print_Area ,我们可以通过.Range("Print_Area")来访问。

如果anoyne怀疑英文名称Print_Area如何在本地化的Office版本中运行,我们将不会遇到任何问题,因为即使名称pipe理器显示了Print_Area的本地化名称, Print_Area