Excelmacros工作缓慢,如何使其更快?
Stackovwerflow社区。
我相信这个问题在这里被问了1000次,但是我只是无法find一个缓慢的macros的解决scheme。
如果input正确的密码,此macros将用于在工作表上取消隐藏某些区域。 取消隐藏的区域取决于单元格的值。 Sheet1上我有一个表格,将某些单元格值与密码相关联。
这是我使用的代码。
1。 部分(从userform开始名为“Pass”确定button点击)
Private Sub CommandButton1_Click() Dim ws As Worksheet DoNotInclude = "PassDB" For Each ws In ActiveWorkbook.Worksheets If InStr(DoNotInclude, ws.Name) = 0 Then Application.ScreenUpdating = False Call Module1.Hide(ws) Application.ScreenUpdating = True End If Next ws End Sub
第二部分。
Sub Hide(ws As Worksheet) Application.Cursor = xlWait Dim EntPass As String: EntPass = Pass.TextBox1.Value If EntPass = Sheet1.Range("G1").Value Then ' Master-Pass, opens all Sheet1.Visible = xlSheetVisible ws.Unprotect Password:="Test" ws.Cells.EntireRow.Hidden = False Pass.Hide Else Dim Last As Integer: Last = Sheet1.Range("A1000").End(xlUp).Row Dim i As Integer For i = 2 To Last Dim region As String: region = Sheet1.Range("A" & i).Value Dim pswd As String: pswd = Sheet1.Range("B" & i).Value If EntPass = pswd Then ws.Unprotect Password:="Test" ws.Cells.EntireRow.Hidden = False Dim b As Integer Dim Last2 As Integer: Last2 = ws.Range("A1000").End(xlUp).Row For b = 2 To Last2 ws.Unprotect Password:="Test" If ws.Range("A" & b).Value <> region Then ws.Range("A" & b).EntireRow.Hidden = True End If If ws.Range("A" & b).Value = "HEADER" Then ws.Range("A" & b).EntireRow.Hidden = False End If ws.Protect Password:="Test" Next b End If Next i End If Application.Cursor = xlDefault Sheet2.Activate Sheet2.Select Pass.Hide End Sub
如果我inputmaster-pass访问每个隐藏区域,但是如果input与cell.value相关的密码,则需要大约5-6分钟才能在每个工作表上取消隐藏所需区域。
如果有人能指出性能下降的原因,并build议修改代码,我会非常感激。 为了以防万一,我已经在这里上传了我的excel文件。
http://www.datafilehost.com/d/d46e2817
Master-Pass是OPENALL,其他密码是“1”到“15”。
先谢谢您,并致以最诚挚的问候。
尝试批量更改:
Dim rngShow as Range, c as range ws.Unprotect Password:="Test" 'move this outside your loop ! For b = 2 To Last2 Set c = ws.Range("A" & b) If c.Value = "HEADER" Then c.EntireRow.Hidden = False Else If c.Value <> region Then If rngShow is nothing then Set rngShow = c Else Set rngShow=application.union(c, rngShow) End If End If End If Next b If Not rngShow is Nothing Then rngShow.EntireRow.Hidden = False ws.Protect Password:="Test" 'reprotect...
您可能还想要切换Application.Calculation = xlCalculationManual
和Application.Calculation = xlCalculationAutomatic
您也可以尝试移动您的Application.Screenupdating
代码循环,它会更新为写入的每个工作表。
Private Sub CommandButton1_Click() Dim ws As Worksheet Application.ScreenUpdating = False ''<- Here DoNotInclude = "PassDB" For Each ws In ActiveWorkbook.Worksheets If InStr(DoNotInclude, ws.Name) = 0 Then Call Module1.Hide(ws) End If Next ws Application.ScreenUpdating = True ''<- Here End Sub