简体   繁体   English

无需先打印预览即可将方向更改为xlLandscape

[英]Change Orientation to xlLandscape without first print preview

I have code that includes changing some of the .PageSetup variables. 我有包含更改某些.PageSetup变量的代码。

I'm having issues where I use this code 我在使用此代码时遇到问题

Sub Test()

    Dim ws as Worksheet

    Set ws = ActiveSheet

    With ws.PageSetup
        .Orientation = xlLandscape
    End With

End Sub

This will error out, but if I pause the code before running .Orientation and go to Print Preview, then try running it, everything works fine. 这将出错,但是如果我在运行.Orientation之前暂停代码并转到“打印预览”,然后尝试运行它,一切正常。

It seems the .PageSetup features need to have the printer settings loaded before being able to execute. 似乎.PageSetup功能需要先加载打印机设置才能执行。 I don't know how to do this with VBA. 我不知道如何用VBA做到这一点。

I am running this from Access DB VBA. 我正在从Access DB VBA运行它。 It exports a table that I then create a new Excel Application to open it with using 它导出一个表,然后创建一个新的Excel应用程序以使用打开它

Dim xlApp as Excel.Application
set xlApp = New Excel.Application

Historically, as long as I have the Excel Reference Library loaded, any VBA I write here works the same in Access as it would in Excel. 从历史上看,只要加载了Excel参考库,我在此处编写的任何VBA在Access中的工作方式都将与在Excel中相同。

But just to compare, I've also had this issue when inside of an Excel file running the VBA, its just not consistent, so I've never figured out what the issue could be. 但是为了比较,当我在运行VBA的Excel文件中时也遇到了这个问题,它只是不一致的,所以我从来没有弄清楚这个问题可能是什么。 But any time I do have the problem, the solution is always just select Print Preview first. 但是,只要我确实遇到问题,解决方案始终是先选择“打印预览”。

This is the error code I get on my specific macro: 这是我在特定宏上看到的错误代码:

Error Number: 1004 错误号:1004

Error Description: Unable to set the Orientation property of the PageSetup class 错误说明:无法设置PageSetup类的Orientation属性

The macro does a ton of queries and table updates before it gets to the Excel export. 宏在进入Excel导出之前会进行大量查询和表更新。 Also, the error message seems to be fairly generic with the 1004 number. 此外,错误消息似乎与1004数字相当通用。

Try turning off Application.PrintCommunication before you work with page setup and then turn it back on afterwards. 在使用页面设置之前,请尝试关闭Application.PrintCommunication ,然后再将其重新打开。 Like this: 像这样:

Application.PrintCommunication = False

With ws.PageSetup
    .Orientation = xlLandscape
End With

Application.PrintCommunication = True

That might just move the error on to the line where you turn print communication back on, though 但是,这可能会将错误移至重新打开打印通讯的行。

您可以尝试将xlLandscape替换为值2。看看xlPageOrientation枚举(Excel)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM