excel listobject.range(x,y).value =的性能非常慢

rlcwz9us  于 2023-04-13  发布在  其他
关注(0)|答案(2)|浏览(126)

所以我有两个我合并的listobject,我想在它们合并成功后获得数据的时间戳。这一切都很好,但是这段代码需要将近2分钟才能完成。2020-11-04 10:46:34 2020- 11-04 10:48:13必须有一个更快的方法。有什么想法吗?(在同一个工作表上声明和分配listobject的是locarget和locource)

Application.ScreenUpdating = false
dtoday = Date
sCreator = Application.UserName

For i = 0 To 350
    loTarget.Range(i, 7).Value = dtoday
    loTarget.Range(i, 8).Value = sCreator
Next i

Application.ScreenUpdating = True
klsxnrf1

klsxnrf11#

ListObject的列

Option Explicit

Sub test()
    
    Application.ScreenUpdating = False

    Dim loTarget As ListObject
    Set loTarget = Sheet1.ListObjects(1)
    
    Dim dtoday As Date
    dtoday = Now ' Now for time, Date for date.
    Dim sCreator As String
    sCreator = Application.UserName
    
    ' For data rows 1 to 350:
'    loTarget.DataBodyRange(1, 7).Resize(350).Value = dtoday
'    loTarget.DataBodyRange(1, 8).Resize(350).Value = sCreator
    
    ' For all data rows:
    loTarget.DataBodyRange.Columns(7).Value = dtoday
    loTarget.DataBodyRange.Columns(8).Value = sCreator
    
    Application.ScreenUpdating = True

End Sub
kqlmhetl

kqlmhetl2#

您可以一次写入一列的所有值。

Application.Calculation = xlManual
With loTarget.Range   
    .Range("G2").Resize(.Rows.Count-1, 1).Value = Date
    .Range("H2").Resize(.Rows.Count-1, 1).Value = Application.UserName
End With
Application.Calculation = xlAutomatic

我跳过了最上面的一行,因为这可能是列标题。请注意,“G2”是相对于表,而不是工作表单元格“G2”(除非您的表以单元格“A1”开始)。
也许速度也可以通过暂时停用计算来提高。

相关问题