我正在尝试编写一个宏,它将遍历选定数量的工作表以隐藏每张工作表上的空行。在专栏#34; 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
答案 0 :(得分:5)
试试这个:
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
块中并使用所有范围对象前面的.
将告诉excel要使用哪个工作表。
同样关闭计算,屏幕更新和关闭事件将有助于加快代码速度,因为它不会暂停执行这些操作。
答案 1 :(得分:1)
AutoFilter method可以快速完成这项工作。选择隐藏下拉列表将非常模仿隐藏行,并添加其他方法来取消隐藏行。
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
没有关于空白的讨论,但可以很容易地将其添加到Criteria2中,XlAutoFilterOperator xlOr 。