VBA在Excelclosures时运行

我有一个挑战,至less对我来说,我是无法处理的。 有人可以帮我或build议在Excelclosures时如何使macros运行?

如何通过VBAclosuresExcel时使macros运行?

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标志定义Public blnClosedVBA as Boolean并在closures工作簿之前将其设置为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 

只有在您自己触发了closures事件的情况下,才会运行该例程。 在例程结束时,将该标志设置为False并触发另一个Workbook.Close将closures工作簿

2:应该为哪个工作簿工作? 它应该是“ThisWorkbook”(您正在运行代码的那个),“ActiveWorkbook”(被激活的那个)还是另一个?

1.如何通过VBAclosures工作簿时运行macros?

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

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

另外,我有问题使这个macros只适用于一个工作簿而不是活动的:

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

 With ActiveSheet.QueryTables.Add(Connection:= _ 

意味着下面的代码将总是针对具有焦点的工作表运行(即,“活动” – 如果您input了某些内容,将接收键盘input的工作表)。 这就是ActiveSheet所做的。 尝试用`ActiveSheet with something like ThisWorkbook.Sheet1的方法replace`ActiveSheet with something like , where Sheet1是VBA编辑器中“Properties”窗口中显示“(Name)”的表的名称。