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