Excel关闭时VBA运行

时间:2013-03-22 10:02:47

标签: excel vba excel-vba

我有一个挑战,至少对我来说,我显然无法应对。在Excel关闭时,有人可以帮助我或建议如何使宏运行吗?

如何通过VBA关闭Excel时运行宏?

Sub Upload0()
    ' Upload Webpage content
    Application.OnTime Now + TimeValue("00:00:15"), "Upload0"

    With ActiveSheet.QueryTables.Add(Connection:= _
        "URL;http://cetatenie.just.ro/ordine/articol-11", Destination:=Range("A1"))
        .Name = "CetatenieOrdine"
        .FieldNames = True
        .RowNumbers = False
        .FillAdjacentFormulas = False
        .PreserveFormatting = True
        .RefreshOnFileOpen = True
        .BackgroundQuery = True
        .RefreshStyle = xlOverwriteCells
        .SavePassword = True
        .SaveData = True
        .AdjustColumnWidth = True
        .RefreshPeriod = 1
        .WebSelectionType = xlEntirePage
        .WebFormatting = xlWebFormattingNone
        .WebPreFormattedTextToColumns = True
        .WebConsecutiveDelimitersAsOne = True
        .WebSingleBlockTextImport = False
        .WebDisableDateRecognition = False
        .WebDisableRedirections = False
        .Refresh BackgroundQuery:=False
    End With

' Deletes empty cells
Columns("A:A").Select
Selection.SpecialCells(xlCellTypeBlanks).Select
Selection.Delete Shift:=xlUp

' Adjust column width and delet useless rows
Rows("1:31").Select
Selection.Delete Shift:=xlUp
Range("B28").Select
Selection.End(xlDown).Select
Rows("17:309").Select
Selection.Delete Shift:=xlUp

End Sub

非常感谢大家!

2 个答案:

答案 0 :(得分:1)

1:在模块Public blnClosedVBA as Boolean中定义一个布尔标志,并在关闭工作簿之前在VBA例程中将其设置为true。然后在Workbook_BeforeClose事件处理程序(在ThisWorkbook下),执行以下操作:

If blnClosedVBA = True Then 
Cancel = True 'Stops the workbook from closing
'Rest of your code here
blnClosedVBA = False ' Set so next time you try to close the workbook, it actually closes
'Workbook.Close or ThisWorkbook.Close - depends on your answer to my question below

仅当您自己触发了关闭事件时才会运行例程。在例程结束时,将标志设置为False并触发另一个Workbook.Close将关闭工作簿

2:哪个工作簿应该适用?它应该是'ThisWorkbook'(您运行代码的那个),'ActiveWorkbook'(激活的那个)还是另一个?

答案 1 :(得分:1)

  

1.通过VBA关闭工作簿时,如何使宏运行?

简短回答:你做不到。您的代码是工作簿的一部分,除非在Excel中加载工作簿,否则它无法运行。您可能能够将代码移动到您选择在Excel启动时默认加载的单独加载项工作簿(使用“Excel选项|加载项”)。但Excel仍然需要在您的计算机上运行。

您可以编写一个完全独立的程序来执行您想要的操作,将Web查询的结果写入Excel工作簿。我假设您希望工作簿在您自己引用时(当Excel正在运行时)或其他资源时始终包含最新数据。如果你可以获得Visual Basic 6的副本(可能无法合法地实现这一点),那么这在语法上与VBA基本相同。接下来最接近的是VB.Net。这在技术上有点复杂。

  

2.另外,我有问题使这个宏仅适用于一个工作簿而不是活动工具:

我们可以处理这一行:这一行:

With ActiveSheet.QueryTables.Add(Connection:= _

表示以下代码将始终针对具有焦点的工作表(即“活动” - 如果键入内容将接收键盘输入的工作表)。这就是ActiveSheet的作用。尝试替换`ActiveSheet with something like ThisWorkbook.Sheet1 , where Sheet1`是您在VBA编辑器的“属性”窗口中看到的表单的名称,其中显示“(名称)”。