我创建了一个宏,它隐藏了特定单元格的特定列中的值不存在的所有行。
我有这段代码:
在endrow = 6的时刻,这是运行宏直到第6行,但我实际上希望它做的是将结束行作为最后一行数据然后停止。
我不确定如何尝试通过列函数进行循环。
有什么想法吗?
Sub Hidemacro()
BeginRow = 1
EndRow = 6
ChkCol = 5
For RowCnt = BeginRow To EndRow
If Cells(RowCnt, ChkCol).Value = "" Then
Cells(RowCnt, ChkCol).EntireRow.Hidden = True
Else
Cells(RowCnt, ChkCol).EntireRow.Hidden = False
End If
Next RowCnt
End Sub
答案 0 :(得分:0)
请改为尝试:
Sub Hidemacro()
'set a reference to active sheet
Dim sht As Worksheet
Set sht = Application.ActiveSheet
'set macro variables
Dim BeginRow As Long
Dim EndRow As Long
Dim ChkCol As Long
'set up variables
BeginRow = 1
EndRow = sht.Cells(Rows.Count, "A").End(xlUp).Row
Debug.Print EndRow
ChkCol = 5
'do the hiding of rows - your original code plus sht reference
For RowCnt = BeginRow To EndRow
If sht.Cells(RowCnt, ChkCol).Value = "" Then
sht.Cells(RowCnt, ChkCol).EntireRow.Hidden = True
Else
sht.Cells(RowCnt, ChkCol).EntireRow.Hidden = False
End If
Next RowCnt
End Sub
答案 1 :(得分:0)
因为我心情很好,这里有一个“单行”,它会隐藏ChkCol
中所有空单元格的行(此处为第1列,但您可以明显更改它)
Option Explicit
Sub Hidemacro()
Const ChkCol As Long = 1
Range(Cells(1, ChkCol), Cells.Find("*", Cells(1, ChkCol), xlFormulas, , xlByRows, xlPrevious)).SpecialCells(xlCellTypeBlanks).EntireRow.Hidden = True
End Sub
扩展此概念以在宏中使用以隐藏ChkCol
中的单元格为空或包含空字符串的行;并考虑到明确定义运行宏的工作表通常是一件好事(在下面的宏中,如果你愿意,你可以明确Set WS = ActiveSheet
,如果你真的想要这个功能),我建议如果你有很多行,可能会运行得更快:
Option Explicit
Sub Hidemacro()
Const ChkCol As Long = 1
Const BeginRow As Long = 1
Dim WS As Worksheet
Dim myRange As Range, R As Range
Set WS = Worksheets("sheet1")
Application.ScreenUpdating = False
With WS
.Cells.EntireRow.Hidden = False
With Range(.Cells(BeginRow, ChkCol), .Columns(ChkCol).Find( _
what:="*", _
after:=.Cells(BeginRow, ChkCol), _
LookIn:=xlFormulas, _
searchorder:=xlByRows, _
searchdirection:=xlPrevious))
.SpecialCells(xlCellTypeBlanks).EntireRow.Hidden = True
For Each R In .SpecialCells(xlCellTypeVisible).Cells
If Len(R.Text) = 0 Then R.EntireRow.Hidden = True
Next R
End With
End With
Application.ScreenUpdating = True
End Sub