我在excel打开时尝试清除打印区域和自动过滤: 在Excel vba中总是新手所以在谷歌上搜索下面的代码 这个代码我已经在XLstart文件夹中放入了ThisWorkbook of Personal.xlsb,并且当前宏安全性已设置为启用所有宏
Option Explicit
Public WithEvents xlApp As Excel.Application
Private Sub Workbook_Open()
Set xlApp = Application
End Sub
Private Sub Workbook_Close()
Set xlApp = Nothing
End Sub
Private Sub xlApp_WorkbookOpen(ByVal Wb As Workbook)
Application.EnableEvents = False
Call ClrPrntArea
Application.EnableEvents = True
End Sub
这是ClrPrntArea
Sub ClrPrntArea()
Dim ws As Object
For i = 1 To ActiveWorkbook.Worksheets.count
With Worksheets(i)
.PageSetup.PrintArea = ""
.PageSetup.FitToPagesWide = 1
End With
Next
End Sub
我还将在个人xlsb中对模块进行另一次宏调用,以便在上面开始工作后重置自动调整器。任何输入都将非常有用
答案 0 :(得分:0)
在PERSONAL.xlsb
,模块ThisWorkbook
中,请尝试以下操作;它与你的请求中的代码几乎相同,有一些modif:
WB
对象变量作为参数,而不是ActiveWorkbook
对象For ... Next
替换为For Each ... Next
并使用本地对象变量PERSONAL.xlsb
本身的陷阱处理如果您感到满意,请删除所有MsgBox语句(以及Else
),它们只是为了显示正在发生的事情以及何时发生。
Private WithEvents Excel_App As Excel.Application
' runs when Excel_App encounters a Workbook_Open() event
Private Sub Excel_App_WorkbookOpen(ByVal WB As Workbook)
Dim WS As Worksheet
If WB.Name <> "PERSONAL.xlsb" Then
MsgBox "PERSONAL.xlsb: Excel_App_WorkbookOpen(): " & WB.Name
For Each WS In WB.Worksheets
WS.PageSetup.PrintArea = ""
WS.PageSetup.FitToPagesWide = 1
If WS.FilterMode Then
WS.ShowAllData
End If
Next
Else
MsgBox "PERSONAL.xlsb: Excel_App_WorkbookOpen(): myself"
End If
End Sub
' runs when PERSONAL.xlsb is opened
' assign current Excel application to object variable Excel_App
Private Sub Workbook_Open()
MsgBox "PERSONAL.xlsb: Workbook_Open()"
Set Excel_App = Application
End Sub
注意:
当双击 Excel文件(例如,在桌面上)时,事件处理程序未启动时,请关闭所有Excel应用程序并检查任务管理器以查找需要执行的其他孤立Excel进程被杀在玩这个代码时发生在我身上