Excel VBA循环select工作表

我正在尝试编写一个macros,这个macros将循环select大量的工作表来隐藏每个工作表上的空行。 在每个工作表的“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要search哪个表,所以它只search代码开始时的活动表。

把所有内容放在一个With块中,然后使用. 在所有范围对象前面都会告诉excel使用哪张表。

此外,计算,屏幕更新和事件closures将有助于加快代码,因为它不会暂停做这些事情。

AutoFilter方法将使这个快速的工作。 select隐藏下拉菜单将近似模仿隐藏行,以及添加其他方法来隐藏它们。

 Public Sub HideRows() Dim beginRow As Long, endRow As Long, chkCol As Long Dim ndx As Long, arrOne As Variant Application.ScreenUpdating = False beginRow = 10 endRow = 185 chkCol = 1 arrOne = Array("sheet1", "GB", "Adj. B", "Adj. F", "JC-Results", _ "PI-Results", "MK-Results", "TD-Results") For ndx = LBound(arrOne) To UBound(arrOne) With Worksheets(arrOne(ndx)) If .AutoFilterMode Then .AutoFilterMode = False With .Cells(beginRow - 1, chkCol).Resize(endRow - beginRow + 2, 1) .Columns(1).AutoFilter Field:=1, Criteria1:="<>0", _ VisibleDropDown:=False Debug.Print .Address End With End With Next ndx Application.ScreenUpdating = True End Sub 

没有关于空白的讨论,但可以通过xlOr的XlAutoFilterOperator轻松添加到Criteria2。