简化代码以快速同时在12个工作表上执行功能

时间:2014-08-06 10:58:29

标签: performance excel-vba excel-2007 vba excel

我正在使用以下代码,该代码正常运行。

Sub Button2_Click()

Application.ScreenUpdating = False

    Dim rngMyRange As Range
    Dim cell As Range

 Sheets("Jan").Activate
 Sheets("Jan").Select
 Cells.Select
 Selection.EntireRow.Hidden = False
    Set rngMyRange = Range("JanRangeTotal")
    For Each cell In rngMyRange.Cells
        cell.Select
        If cell.Value = "" Then GoTo DOTHETHING
    Next cell

DOTHETHING:
    Selection.Resize(1812).Select
    Selection.EntireRow.Hidden = True

    Sheets("Jan").Select
    Cells.Select
    Selection.Copy
    Sheets(Array("Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec") _
        ).Select
    Sheets("Feb").Activate
    Cells.Select
    Selection.PasteSpecial Paste:=xlPasteFormats, Operation:=xlNone, _
        SkipBlanks:=False, Transpose:=False
    Application.CutCopyMode = False

    Sheets(Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", _
        "Dec")).Select
    Sheets("Feb").Activate
    Range("C7").Select
    Sheets("PO to Complete").Select

Application.ScreenUpdating = True

End Sub

不幸的是,它需要大约15秒的时间才能运行,并且已经切换了屏幕更新,这是大量复制和粘贴运动,这是最耗费时间。所以我想到如何将数组选择进一步提高代码,以便它可以对所有工作表进行DOTHETHING,并且无需复制和粘贴来自" Jan"到所有其他月份表。我想出了下面的代码:

Sub Button2_Click()

    Dim rngMyRange As Range
    Dim cell As Range

 Sheets("Jan").Activate
 Sheets("Jan").Select
 Cells.Select
 Selection.EntireRow.Hidden = False

    Set rngMyRange = Range("JanRangeTotal")
    Sheets(Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", _
    "Dec")).Select
    Sheets("Jan").Activate
    For Each cell In rngMyRange.Cells
        cell.Select
        If cell.Value = "" Then GoTo DOTHETHING
    Next cell

DOTHETHING:
    Selection.Resize(1812).Select
    Selection.EntireRow.Hidden = True
    Range("C7").Select
    Application.CutCopyMode = False

    Sheets("PO to Complete").Select

End Sub

但它没有在其他工作表上执行row-hide命令。有没有办法让我更快地开始工作?

干杯,

邓克

1 个答案:

答案 0 :(得分:0)

为什么使用select命令?这很慢。

我也认为它不像你想象的那样有效。我不认为你可以通过选择跨表来隐藏行,这就是失败的原因。

为什么不尝试在每张纸上声明范围并使用类似

的方式在纸张上循环
application.screenupdating = false
dim ws as worksheet

for each ws in thisworkbook.sheets
    ' Your Code here
next ws

对于声明的范围,这会更快(选择单元格没有意义,除非它是视觉效果,我假设它不是因为你关闭了屏幕更新)