简体   繁体   English

VBA - 检查公式是否在单元格中运行缓慢

[英]VBA - check if formula is in cell runs slow

Here is what I am looking at.这是我正在看的。 I have a sheet that I import part of using the following VBA:我有一张我使用以下 VBA 导入部分的工作表:

Sheets("Sheet1").Select
Range("D1:D1").Select
Selection.QueryTable.Refresh BackgroundQuery:=False

the issue with this is whenever I run it, it messes up the formulas I have in the A and B columns.问题是每当我运行它时,它都会弄乱我在 A 和 B 列中的公式。 So I created a sub that will check for that as follows:所以我创建了一个 sub 将检查如下:

Sub fixAnB()
    Dim sh As Sheet9
    Dim rw As Range
    Set sh = Sheet9
    sh.EnableCalculation = False
    'Sheets("Sheet1")
    Dim i As Long
    i = 0
    Dim f1 As String, f2 As String
    For Each rw In sh.Rows
        i = i + 1
        If i > 1 And sh.Cells(rw.Row, 4).Value <> "" Then
            f1 = "=CONCATENATE(G" & i & ",J" & i & ")"
            f2 = "=CONCATENATE(I" & i & ",H" & i & ",J" & i & ")"
            If sh.Cells(rw.Row, 1).Formula <> f1 Then sh.Cells(rw.Row,    1).Formula = f1
            If sh.Cells(rw.Row, 2).Formula <> f2 Then sh.Cells(rw.Row, 2).Formula = f2
        End If
        If sh.Cells(rw.Row, 4).Value = "" Then Exit For
    Next rw
    sh.EnableCalculation = True
End Sub

my issue with this is that I can have anywhere between 20,000 to 200,000 records on that sheet.我的问题是我可以在该工作表上有 20,000 到 200,000 条记录。 so using the sub to fix the formulas takes about 10 - 15 mins.所以使用 sub 来修复公式大约需要 10 - 15 分钟。 I am looking for one of solutions:我正在寻找解决方案之一:

  1. A way to fix the original problem so it doesn't mess up the references when I import my data一种解决原始问题的方法,这样在我导入数据时就不会弄乱引用

or 2. A way to make that fixer sub run way faster.或 2. 一种使固定器子运行更快的方法。

What do yall think?你怎么看?

Try this code (it takes less than 0.5s on my test on 200000 rows):试试这个代码(我对 200000 行的测试花费不到 0.5 秒):

Sub Test()
 t = Timer
' Application.ScreenUpdating = False
' Application.EnableEvents = False
' Application.Calculation = xlCalculationManual

 Dim sh As Worksheet
 Set sh = ActiveSheet
 Dim i As Long
 i = sh.Range("D1").End(xlDown).Row
 sh.Range("A2:A" & i).Formula = "=CONCATENATE(G2,J2)"
 sh.Range("B2:B" & i).Formula = "=CONCATENATE(I2,H2,J2)"

' Application.ScreenUpdating = True
' Application.EnableEvents = True
' Application.Calculation = xlCalculationAutomatic
 MsgBox Timer - t
End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM