VBA循环非常慢

时间:2018-02-09 04:28:00

标签: excel excel-vba vba

这是一个数据源。

enter image description here

我想做的是:

  1. 列D
  2. 中的每个空单元格中添加 9000
  3. B 栏中连接 D栏 E ,例如C2&"-"&D2
  4. G
  5. 列中添加 E 列和 F

    为此,我编写的代码首先检查单元格 D2 ,如果是empty则添加 9000 。然后它在 B2 中连接 D2 E2 C2&"-"&D2)。然后在 G2 中添加 E2 F2 的值。然后它转到下一行并选择 D3 并检查它是否为empty。代码超过6000行。这是代码:

    Range("D2").Select
    For Count = 1 To (CellsCount - 1)
        If IsEmpty(ActiveCell) Then ActiveCell.Value = 9000
        ActiveCell.Offset(0, -2).Select
        ActiveCell = Cells(1 + Count, 3) & "-" & Cells(1 + Count, 4)
        ActiveCell.Offset(0, 5).Select
        ActiveCell = Cells(1 + Count, 5) + Cells(1 + Count, 6)
        ActiveCell.Offset(1, -3).Select
    Next Count
    

    代码运行大约需要10分钟。如果您能建议我更快地运行代码,我将不胜感激。

    由于

2 个答案:

答案 0 :(得分:3)

立即对所有行执行所有操作,无需循环。

with activesheet
    with .range(.cells(2, "D"), .cells(CellsCount , "D"))
        .specialcells(xlcelltypeblanks) = 9000
        .offset(0, -2).formula = "=c2&""-""&d2"
        .offset(0, -2) = .offset(0, -2).value2    'optional
        .offset(0, 3).formula = "=sum(e2, f2)"
        .offset(0, 3) = .offset(0, 3).value2      'optional
    end with
end with

答案 1 :(得分:1)

不要使用select / offset。喜欢使用单元格(行,列)。

For Count = 1 To (CellsCount - 1)
    If IsEmpty(cells(count,4)) Then cells(count,4)= 9000
    cells(count,2)= Cells(1 + Count, 3) & "-" & Cells(1 + Count, 4)
    cells(count,7)= Cells(1 + Count, 5) + Cells(1 + Count, 6)
Next Count
相关问题