Excel vbscript 填充定义的表非常慢

问题描述 投票:0回答:1

下面的代码在填充大约 300 个单元格的列时执行速度很快(10-15 秒)。但是,在定义的表中填充单元格时,相同的代码运行速度非常慢(10 分钟以上)。我认为这与表格中的范围有关,所以有人知道为什么吗?


Application.DisplayAlerts = False
'Application.ScreenUpdating = False 'this pauses realtime cell populate

Set wb = ThisWorkbook
firstASXrow = 9 'row 9 is the start of my SD data dump

Application.DisplayAlerts = True
Application.ScreenUpdating = True

'set ws to 'SData' sheet
Set ws = wb.Sheets("SData")
ws.Activate

'ASX ticker column
Set tickercode = 12

'find the last ASX ticker in the ticker column
lastASXrow = 300

'MS Stock Code column
Set msStockCode = 10

'populate the MS Stock Code cells
For n = firstASXrow To lastASXrow
    ws.Range(Cells(n, msStockCode.Column), Cells(n, msStockCode.Column)).Value = "XASX:" & ws.Range(Cells(n, tickercode.Column), Cells(n, tickercode.Column)).Value
Continue:
    Next n

'bulk convert all the MS Stock Data cells Stocks DataType (ie. ServiceID268435456)
ws.Range(Cells(firstASXrow, msStockCode.Column), Cells(lastASXrow, msStockCode.Column)).ConvertToLinkedDataType ServiceID:=268435456, LanguageCulture:="en-US"

End Sub
excel macos vbscript excel-365
1个回答
0
投票

您在使用表格时看到的速度减慢通常来自 Excel 处理 ListObjects 的方式。表具有额外的功能(自动扩展、结构化引用和重新计算公式),这些功能可能会减慢代码执行速度。

关闭自动重新计算:更新表格时,Excel 可能会不断重新计算公式

Application.Calculation = xlCalculationManual

使用批量更新而不是循环遍历每个单元格:不要在循环中一次更新一个单元格,而是将值加载到数组中,修改数组,然后一次将整个内容写回到工作表中。这减少了与表格交互的次数(这是缓慢的部分)。

例如:

Dim dataArray() As Variant
Dim i As Long

' Load data into an array
dataArray = ws.Range(Cells(firstASXrow, tickercode.Column), Cells(lastASXrow, tickercode.Column)).Value

' Update the array
For i = 1 To UBound(dataArray, 1)
    dataArray(i, 1) = "XASX:" & dataArray(i, 1)
Next i

' Write the array back to the worksheet
ws.Range(Cells(firstASXrow, msStockCode.Column), Cells(lastASXrow, msStockCode.Column)).Value = dataArray

如果不需要,请禁用表自动扩展

保持屏幕更新和显示警报关闭

Application.ScreenUpdating = False
Application.DisplayAlerts = False
© www.soinside.com 2019 - 2024. All rights reserved.