vba - Excel VBA 循环选择工作表

标签 vba excel

我正在尝试编写一个宏,它将循环遍历选定数量的工作表以隐藏每张工作表上的空行。在每个工作表的“A”列中包含一个 1 或一个 0。如果是 0,我想隐藏该行。

这是我从各个网站收集的代码。我最大的挑战是知道我需要操纵哪些对象。

enter code here
Public Sub HideRows()
Dim beginRow As Double
Dim endRow As Double
Dim ChkCol As Double
Dim RowCnt As Double
Dim ws As Worksheet
Dim ArrayOne As Variant
Dim InxW As Long

beginRow = 10
endRow = 185
ChkCol = 1

ArrayOne = Array("GB", "Adj. B", "Adj. F", "JC-Results", "PI-Results", "MK-Results", "TD-Results")


For InxW = LBound(ArrayOne) To UBound(ArrayOne)
    For RowCnt = beginRow To endRow
    If Cells(RowCnt, ChkCol).Value = 0 Then
        Cells(RowCnt, ChkCol).EntireRow.Hidden = True
    Else
        Cells(RowCnt, ChkCol).EntireRow.Hidden = False
    End If
    Next RowCnt

Next



End Sub

最佳答案

试试这个:

Public Sub HideRows()
Dim beginRow As Double
Dim endRow As Double
Dim ChkCol As Double
Dim RowCnt As Double
Dim ws As Worksheet
Dim ArrayOne As Variant
Dim InxW As Long

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

beginRow = 10
endRow = 185
ChkCol = 1

ArrayOne = Array("GB", "Adj. B", "Adj. F", "JC-Results", "PI-Results", "MK-Results", "TD-Results")


For InxW = LBound(ArrayOne) To UBound(ArrayOne)
    With Sheets(ArrayOne(InxW))
        For RowCnt = beginRow To endRow
            If .Cells(RowCnt, ChkCol).Value = 0 Then
                .Rows(RowCnt).Hidden = True
            Else
                .Rows(RowCnt).Hidden = False
            End If
        Next RowCnt
    End With

Next InxW

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

End Sub

主要问题是您没有告诉 Excel 要搜索哪个工作表,因此它仅搜索代码开始时的事件工作表。

通过将所有内容放入 With block 中并在所有范围对象前面使用 . 将告诉 excel 使用哪个工作表。

此外,关闭计算、屏幕更新和事件将有助于加快代码速度,因为它不会暂停执行这些操作。

关于vba - Excel VBA 循环选择工作表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34934933/

相关文章:

excel - 如何将整个工作表复制到引用 Excel 中工作表名称的新创建工作表?

Excel 工作簿打开事件宏并不总是运行

Ruby Axlsx 如何添加包含合并单元格的行

python - 如何让unoconv在转换为pdf之前自动计算公式?

excel - 当 Excel 从 Outlook 中的宏打开时,如何阻止 Excel 打开用户窗体?

Excel (VBA) : Disabling cell formatting except bold font

vba - Word 中的 Visual Basic 宏以调整大小/居中/删除所有图像

html - 将 CSV 数据从 Web 服务导入 Excel

vba - 如何在Word的VBA中使用COM?

excel - 如何用VBA和选择器将该网站的内容导出到Excel?