【发布时间】:2014-06-17 05:03:37
【问题描述】:
我正在尝试自动化具有 5 个不同信息源的报告。我试图使用 ListObjects 将不同表的 UNION 合并为一个,除了复制第一个 ListObject 的第一列时,一切正常。复制第一列大约需要 2 分钟,接下来的列不到 1 秒。
每次运行 VBA 脚本时,我都会删除目标表的所有行,以使用 0 行的 ListObject 启动 VBA 脚本。
我将尝试解释它是如何工作的:
Sub ProcesarPresupuesto()
'This is the first macro that process and copy the information of the first source
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Application.Calculation = xlCalculationManual
'<Here> I add several columns and process the information of this first source, I keep all the rows as values using the Function: AddColumnFormula (at the end of this example). I think this is not causing the problem.
'Then I fill all the Blanks Cells to avoid having empty cells in my final table.
Sheets("Origin").Select
Selection.CurrentRegion.Select
On Error Resume Next
Selection.SpecialCells(xlCellTypeBlanks).FormulaR1C1 = "Null"
On Error GoTo 0
'When I have the ListObject ready I start copying the columns to the destination
Sheets("Destination").Select
Range("A1").Select
While ActiveCell.Value <> ""
Call CopyColumn("Origin", ActiveCell.Value, "Destination")
ActiveCell.Offset(0, 1).Select
Wend
End Sub
我认为这应该非常快。如果我只删除目标 ListObject 的值并将行保持为空,则会立即复制第一列,因此我认为问题与 Excel 如何计算要添加到 ListObject 的第一行有关。当表为空时,是否有更好的方法来复制列?我真的做错了什么吗?
这是函数 CopyColumn
Function CopyColumn(Origin, ColumnName, Destination)
Range(Origin & "[[" & ColumnName & "]]").Copy Destination:=Range(Destination & "[[" & ColumnName & "]]")
End Function
这是我用来处理列的函数
Function AddColumnFormula(DestinationSheet, TableName, ColumnName, Value)
Set NewColumn = Sheets(DestinationSheet).ListObjects(TableName).ListColumns.Add
NewColumn.Name = ColumnName
Set Rango = Range(TableName & "[[" & ColumnName & "]]")
Rango.Value = Value
Rango.Copy
Rango.PasteSpecial (xlPasteValues)
End Function
提前感谢您的时间和回答
【问题讨论】:
-
这个范围的地址是什么?
Range(Origin & "[[" & ColumnName & "]]")?添加MsgBox Range(Origin & "[[" & ColumnName & "]]").Address,我们看看它显示了什么。 -
感谢@DavidZemens 的帮助,它为我提供了 Range($A$2:$A$42174) 源代码中第一列的范围。好像没问题。
-
嗯。我在 45,000 行数据上运行您的代码,复制 7 列(screenupdating = False)不到一秒,screenupdating = True 不到 2 秒...
-
嗨@DavidZemens 我在周末尝试过这个工作,但我并不走运。这是我的文件的一个示例。我删除了一些不用于此宏的工作表。这里奇怪的是,当我在另一台计算机上测试它时,它工作得更好,但它仍然很慢。宏被调用:ProcesarPresupuesto,它位于模块“GenerarReporte”link
-
我跑了一次,速度有点慢,但我没有计时。然后我对ProcessarPresupuesto做了一些改动,花了1m16s。我又尝试了一些不同的成功,最近花了 3 分钟 13 秒,但大多数处决每次大约 2 分钟。在那次尝试中,我放入了一些 Debug.Print 语句,我认为问题出在
...CurrentRegion.SpecialCells(xlCellTypeBlanks)上——该语句需要 2 分 53 秒来评估。我会再看一会儿,但我认为这是罪魁祸首:CurrentRegion和SpecialCells都是昂贵的操作。可能有更好的方法来做到这一点。
标签: excel vba performance listobject