gpt4 book ai didi

vba - 压缩大量(不切实际的)基于循环的 VBA 代码;嵌套 For...Next 循环

转载 作者:行者123 更新时间:2023-12-03 02:02:53 25 4
gpt4 key购买 nike

大家好,让我们首先介绍一下我的项目的一些简短背景,然后我将跟进我的具体问题和代码。

目前我正在构建一个程序来自动执行填充模板的过程。该模板的数据经常超过 60,000 行,我通过插入新的数据表并运行它来构建其中的大部分,以便每月工作。目前,所有工作都基于我手动导入 Excel 的一张数据表。该数据表不包含填充模板所需的所有数据,因此现在我开始引入其他数据来补充这一点。这里的问题在于数据关联。当我最初从一张数据表中提取数据时,我不必担心为每一行提取的数据是否与其他行一致,因为它们都来自同一张数据表。现在,我必须交叉检查两张表中的数据,以确认它提取的是正确的信息。

现在是您需要了解的内容。我正在尝试填写一个称为“理发”的列,但在此之前,我需要确认我正在提取与贸易 ID 相关的正确理发编号,该 ID 已填充到上一行的模板中代码。

使用我在整个项目中一直使用的类似逻辑,这是我必须执行此任务的代码片段。

    Dim anvil as Worksheet
Dim ALLCs as worksheet
Dim DS as worksheet
'''''''''''''''''''''''''''''code above this line is irrelevant to answer this question
ElseIf InStr(1, DS.Cells(x, 2), "Haircut") Then
Anvil.Select
For y = 1 To 80
If Anvil.Cells(1, y) = "Haircut" Then
For Z = 1 To 80
If Anvil.Cells(1, Z) = "Trade ID" Then
For t = 2 To 70000
For u = 16 To 70000
If Anvil.Cells(t, Z) = ALLCs.Cells(u, 34) Then
ALLCs.Cells(u, 27) = Anvil.Cells(t, y)
End If
Next
Next
End If
Next
End If
Next

这段代码与我的其他代码相结合,我认为理论上可以工作,但我只能想象这将花费令人难以置信的时间(这个程序已经需要 7 分半钟才能运行)。关于如何遵循此一般逻辑以更好的功能重写此代码有什么建议吗?

无论您完全修改代码,还是提供有关如何减少循环的建议,我们都将不胜感激。除了屏幕更新和计算建议之外,我还在寻找总体上加速代码的建议。

最佳答案

如果我正确理解了逻辑,那么您可以使用 .Find() 方法替换除一个循环之外的所有循环,如下所示:

'// Dimension range objects for use
Dim hdHaricut As Excel.Range
Dim hdTradeID As Excel.Range
Dim foundRng As Excel.Range

With Anvil
With .Range("A1:A80") '// Range containing headers
'// Find the cell within the above range that contains a certain string, if it exists set the Range variable to be that cell.
Set hdHaircut = .Find(What:="Haircut", LookAt:=xlWhole)
Set hdTradeID = .Find(What:="Trade ID", LookAt:=xlWhole)
End With
'// Only if BOTH of the above range objects were found, will the following block be executed.
If Not hdHaricut Is Nothing And Not hdTradeID Is Nothing Then
For t = 2 To 70000
'// Using the .Column property of the hdTradeID range, we can see if the value of Cells(t, hdTradeColumn) exists
'// in the other sheet by using another .Find() method.
Set foundRng = ALLCs.Range(ALLCs.Cells(16, 34), ALLCs.Cells(70000, 34)).Find(What:=.Cells(t, hdTradeID.Column).Value, LookAt:=xlWhole)
'// If it exists, then pass that value to another cell on the same row
If Not foundRng Is Nothing Then ALLCs.Cells(foundRng.Row, 27).Value = .Cells(t, hdHaircut.Column).Value
'// Clear the foundRng variable from memory to ensure it isn't mistaken for a match in the next iteration.
Set foundRng = Nothing
Next
End If
End With

关于vba - 压缩大量(不切实际的)基于循环的 VBA 代码;嵌套 For...Next 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29808082/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com