帮助我优化 VBA Excel 代码,以便将工作表上每一行的某些列复制到另一个工作表上

发布于 2024-09-11 05:23:58 字数 907 浏览 4 评论 0原文

我需要将工作表 A 中每一行的某些列复制到工作表 B 中。

我创建了一个子项目,它创建了匹配列号的 2 个数组(变体),因此我可以将工作表 A 中的第 3 列映射为等于工作表 B 中的第 8 列工作表 B 等。

一切正常,问题是它相当慢,这里是:

Sub insertIntoSelectedOpps(opCols As Variant, siebelCols As Variant, ByVal length As Integer)

Dim insertRange As Range
Dim siebelRange As Range
Dim rowCount As Integer

Set insertRange = shSelected.Range("a3", "bb4") 'very wide table!'
Set siebelRange = shDatabase.UsedRange.Rows

rowCount = siebelRange.Rows.count

MsgBox "siebel row count: " & rowCount

For i = 2 To rowCount

    Set insertRange = shSelected.Range("a3", "bb4")
    insertRange.Insert

    For x = 1 To length - 1
        If opCols(x) <> -1 Then 'unequal to -1'
            insertRange.Cells(1, opCols(x)).value = siebelRange.Cells(i, siebelCols(x)).value
        End If
    Next x

Next i
End Sub

不要担心 IF 情况,这是业务逻辑,以防映射中的列名称找不到。

I need to copy certain columns of every row in sheet A into sheet B.

I have created a sub that creates 2 arrays (variants) of the matching column numbers, so I can map column 3 in sheet A to be equal to column 8 in sheet B, etc.

Everything works fine, thing is it's quite slow, here it is:

Sub insertIntoSelectedOpps(opCols As Variant, siebelCols As Variant, ByVal length As Integer)

Dim insertRange As Range
Dim siebelRange As Range
Dim rowCount As Integer

Set insertRange = shSelected.Range("a3", "bb4") 'very wide table!'
Set siebelRange = shDatabase.UsedRange.Rows

rowCount = siebelRange.Rows.count

MsgBox "siebel row count: " & rowCount

For i = 2 To rowCount

    Set insertRange = shSelected.Range("a3", "bb4")
    insertRange.Insert

    For x = 1 To length - 1
        If opCols(x) <> -1 Then 'unequal to -1'
            insertRange.Cells(1, opCols(x)).value = siebelRange.Cells(i, siebelCols(x)).value
        End If
    Next x

Next i
End Sub

Don't worry bout the IF case, it's business logic in case a column name in the mapping wasn't found.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

喜你已久 2024-09-18 05:23:58

通常,在进行大量处理之前停止屏幕更新和计算是一个好主意:

msgbox 之后:

Application.ScreenUpdating = False
xlCalc = Application.Calculation
Application.Calculation = xlCalculationManual

next 之后

Application.Calculation = xlCalc
Application.ScreenUpdating = True

这应该会加快速度。另外,请查看此页面以进行更多速度调整

Usually, stopping screen updates and calculation before a large treatment is a good idea:

After the msgbox:

Application.ScreenUpdating = False
xlCalc = Application.Calculation
Application.Calculation = xlCalculationManual

After the next

Application.Calculation = xlCalc
Application.ScreenUpdating = True

This should speed things. Also, take a look at this page for some more speed tweaks

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文