Excel 关闭时运行 VBA

标签 vba excel

我面临一个挑战,至少对我来说,我显然无法应对。有人可以帮助我或建议如何在 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

非常感谢大家!

最佳答案

1:在模块 Public blnClosedVBA as Boolean 中定义 bool 标志,并在关闭工作簿之前在 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”(激活的工作簿)还是其他工作簿?

关于Excel 关闭时运行 VBA,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15567524/

相关文章:

VBA中的Excel公式

vba - 为 ADO 构造正确的 SQL 字符串以获取具有 MAX Date 的数据

javascript - excel插件和基于 Electron 的桌面应用程序之间的通信

vba - 启动 Windows 资源管理器并突出显示文件

ms-access - MS Access VBA 交叉表报告图例排序顺序

excel - 打开工作簿下标超出范围

sql-server - 将范围从 Excel 复制到 SQL 而不使用 For 循环?

excel - 在文本框 1 中找到 ID 以查找未将复选框选择应用于该行的行

sql-server - 为什么 SSIS 忽略我从 Excel 源导入的最后一列?

vba - 将数据从 SQL Server 加载到 Excel 的最快方法