1

当excel打开时,我试图清除打印区域和自动过滤器:我是Excel vba中的新手,所以从谷歌搜索中组装了以下代码我已经把这个代码放在了XLstart文件夹中Personal.xlsb的ThisWorkbook中,当然宏安全性已设置为启用所有宏

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 中对模块进行另一个宏调用,以重置自动调整器。任何输入都会非常有帮助

4

1 回答 1

0

PERSONAL.xlsb, moduleThisWorkbook中,试试下面的;它与您的请求中的代码几乎相同,但有一些修改:

  • 应用程序对象声明为私有
  • 事件例程使用WB作为参数传递的局部对象变量,而不是ActiveWorkbook对象
  • For ... NextFor 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 进程。在玩这个代码时发生在我身上

于 2013-06-10T06:58:18.810 回答