【问题标题】:Adding a selection of a non-contiguous space to an existing selection in an Excel macro将非连续空间的选择添加到 Excel 宏中的现有选择中
【发布时间】:2011-12-04 05:52:42
【问题描述】:

我有一个文档,我将根据用户的个人需求,将其分发给具有任意行数(相同列数)的三个不连续组的用户。 我当前的宏运行速度很慢,所以我想知道是否有人可以提出比我这里更好的解决方案,或者至少为我指出内置函数可能有助于我正在做的事情的方向。

在下面的脚本中,我将其设置为作用于以下行中的数据:6、8-19、21-60、63-81。

所有这一切都是为了删除第一列数据 (sFirstCol = "D") 中的值,并将适用行中所有列 (E->AC) 中的值移动到左侧一个单元格,将最右边的列值留空。

Sub RollOver1()
    Dim sFirstCol As String
    Dim sSecCol As String
    Dim sSLastCol As String
    Dim sLastCol As String
    Dim iFirstRow As Integer
    Dim iLastRow As Integer
    Dim excludeRows() As Variant

    sFirstCol = "D"
    sSecCol = "E"
    sSLastCol = "AB"
    sLastCol = "AC"
    iFirstRow = 6
    iLastRow = 81
    excludeRows = Array(7, 20, 61, 62)



    For i = iFirstRow To iLastRow
        Dim bExcludedRow As Boolean
        bExcludedRow = False
        For Each eR In excludeRows
            If eR = i Then
                bExcludedRow = True
            End If
        Next
        If bExcludedRow = False Then
            Range(sSecCol + LTrim(Str(i)) + ":" + sLastCol + LTrim(Str(i))).Select
            Selection.Copy
            Range(sFirstCol + LTrim(Str(i)) + ":" + sSLastCol + LTrim(Str(i))).Select
            ActiveSheet.PasteSpecial Format:=3, Link:=1, DisplayAsIcon:=False, IconFileName:=False
            Range(sLastCol + LTrim(Str(i))).Select
            Selection.ClearContents
        End If
    Next

    Range(sFirstCol + LTrim(Str(iFirstRow + 1))).Select
    ActiveCell.FormulaR1C1 = "='Sheet1'!R[4]C[2]"
    Range(sLastCol + LTrim(Str(iFirstRow))).Select
    ActiveCell.FormulaR1C1 = "=RC[-1]+7"

    Range("A1").Select

End Sub

【问题讨论】:

    标签: excel vba range selection


    【解决方案1】:

    以下是一些可以加快您的代码速度的指针:

    Dim所有变量

    Dim i As long
    Dim eR As variant
    

    在您的例程开始时,将计算设置为手动,关闭屏幕更新和事件。

    Application.ScreenUpdating = False
    Application.Calculation = xlCalculationManual
    Application.EnableEvents = False
    

    最后再打开它们

    Application.ScreenUpdating = True
    Application.Calculation = xlCalculationAutomatic
    Application.EnableEvents = true
    

    不要Select 要处理的范围。设置一个变量并对其采取行动。示例:

    Dim rng as Range
    Set rng = Range(sSecCol + LTrim(Str(i)) + ":" + sLastCol + LTrim(Str(i)))
    rng.Copy
    

    不要一次只对一张纸进行操作,而是在一个连续的范围内操作。在这种情况下,这将涉及一些更复杂的计算来计算排除行之间的行,但它会带来净收益。

    有很多方法可以“移动”数据,其中一些可能比复制、粘贴、清除更快。但是,一旦您应用了上述提示,您可能会发现例程运行得足够快。如果没有,请重新发布。

    【讨论】:

    • +1 - 一般但仍然非常好的提示。顺便说一句,您还可以在模块的开头添加一个Option Explicit,以便您将强制声明每个变量
    • 太棒了,感谢克里斯的这些建议。仅在宏期间禁用事件/更新将运行时间从约 30 秒减少到 2-3 秒。此外,了解在将来使用循环变量之前声明循环变量的性能优势也很有用。
    猜你喜欢
    • 1970-01-01
    • 2022-11-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-15
    • 1970-01-01
    • 2022-11-12
    • 2017-11-30
    • 1970-01-01
    相关资源
    最近更新 更多