excel - 如何在 Excel 中加速这个 vb 代码

标签 excel vba

我在 Excel 工作表中使用以下代码进行计算。不幸的是,计算时间太长,页面不断闪烁。

    Private Sub Worksheet_Activate() 
    BeginRow = 1  
    EndRow = 300
    ChkCol = 3

     For RowCnt = BeginRow To EndRow
     If Cells(RowCnt, ChkCol).Value = "B" Then
     Cells(RowCnt, ChkCol).EntireRow.Hidden = True
     Else
     Cells(RowCnt, ChkCol).EntireRow.Hidden = False
     End If
     Next RowCnt     
     End Sub

这是一个考勤管理软件,有4张。除了 Sheet1 之外,我对所有工作表都使用此代码.主数据输入 sheet1 .
请帮助我加快这个过程。

最佳答案

我同意@BK201,您也可以使用自动过滤器。这是另一种更快的方法。我说得更快是因为它不会在循环中显示/隐藏行。此外,您可以在 Application.ScreenUpdating = false 之间对您的代码进行打磨。和 Application.ScreenUpdating = true按照@KazJaw 的建议停止闪烁。

Option Explicit

Private Sub Worksheet_Activate()
    Dim BeginRow As Long, EndRow As Long
    Dim ChkCol As Long, RowCnt As Long
    Dim rngHide As Range

    BeginRow = 1: EndRow = 300: ChkCol = 3

    '~~> Unhide all the rows
    Rows("1:300").EntireRow.Hidden = False

    '~~> Loop through the rows and identify which rows needs to be hidden
    For RowCnt = BeginRow To EndRow
        If Cells(RowCnt, ChkCol).Value = "B" Then
            If rngHide Is Nothing Then
                Set rngHide = Rows(RowCnt)
            Else
                Set rngHide = Union(rngHide, Rows(RowCnt))
            End If
        End If
    Next RowCnt

    '~~> Hide the rows  in one go
    If Not rngHide Is Nothing Then rngHide.EntireRow.Hidden = True
End Sub

关于excel - 如何在 Excel 中加速这个 vb 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20451336/

相关文章:

vba - 在 VBA 中比较字符串的最佳方法?

excel - 打包和分发 Excel 应用程序的最佳方式是什么

vba - 在 Excel 2013 加载项中插入列失败并出现错误 438

arrays - 作为类属性的变体类型的 VBA 数组

excel - VBA Excel在下拉框上设置焦点

excel - 在 Tableau 中创建模板以使相似的 Excel 文件之间的移动更加顺畅

excel - 搜索特定的列标题名称,复制列并粘贴以附加到另一个 wookbooksheet

c# - 带有 .Net5.0 的 Microsoft Interop Excel 无法正常工作

excel - 如何将单元格值定义到工作簿中每个工作表的同一列VBA

string - 使用 html 字符串后,VBA 查询表不会将数据拉入工作表