当我尝试您的代码时,出现以下语法错误:
- myRange 未定义。
- 行(如在 myRange(Row) 中)未定义。
您的代码的其他问题:
- myRange 是一个范围,因此 IsNumeric(myRange) 将始终为 false。
If Application.CountBlank(myRange) <> myRange.Cells.Count
表示不隐藏空白行。
IsNumeric 和 IsNumber 都对单个值进行操作。我在文档中找不到任何建议可以使它们对数组、集合或范围进行操作。我的实验产生了与此一致的结果。除了检查一行中的单个单元格之外,我不相信有任何方法可以处理困难的情况。
我想我已经针对所有边界条件测试了以下代码,但我不能保证这一点。它隐藏空白行和只包含零的行。如果选择了一个范围,则该范围之外的列将被视为空白。
Sub HideRows()
Dim ColCrnt As Integer
Dim Hide As Boolean
Dim myRange As Range
Dim R As Long
Dim Rng As Range
If Selection.Rows.Count > 1 Then
Set Rng = Selection
Else
Set Rng = ActiveSheet.UsedRange
End If
For R = 1 To Rng.Rows.Count
Set myRange = Range(Rng(R, 1), Rng(R, Rng.Columns.Count))
If Application.CountBlank(myRange) = myRange.Cells.Count Then
' Blank row
Hide = True
ElseIf Application.Sum(myRange) <> 0 Then
' At least on numeric cell with a non-zero value
Hide = False
Else
' Row contains one or more cells containing text, booleans or zeroes
' Hide if all these cells are zeros.
ColCrnt = Rng.Columns.Count
Set myRange = Rng(R, ColCrnt)
If IsCellZero(myRange) Or IsEmpty(myRange) Then
' Last cell of row is zero or blank so will have to check row
Do While True
' Skip to first non-blank cell to left or column 1
' if no non-blank cells
Set myRange = myRange.End(xlToLeft)
If myRange.Column < Rng(R, 1).Column Then
' Have move outside selection
Hide = True
Exit Do
End If
If myRange.Column = Rng(R, 1).Column Then
' Have reached column 1
If IsCellZero(myRange) Or IsEmpty(myRange) Then
' Column 1 is zero or blank so nothing interesting on row
Hide = True
Exit Do
Else
' Column 1 is not zero or blank
Hide = False
Exit Do
End If
End If
If Not IsCellZero(myRange) Then
Hide = False
Exit Do
End If
If myRange.Column = Rng(R, 1).Column Then
' No non-zero cells found
Hide = True
Exit Do
End If
Loop
Else
' Last cell of row is neither zero nor empty
Hide = False
End If
End If
If Hide Then
Rng.Rows(R).Hidden = True
Else
Rng.Rows(R).Hidden = False
End If
Next R
End Sub
Function IsCellZero(Rng As Range) As Boolean
' Rng must be a single cell. Returns true only if Rng.Value is numeric zero
' Function uses IsNumber because IsNumeric returns True
' for empty cells and booleans
If Application.WorksheetFunction.IsNumber(Rng.Value) Then
If Val(Rng.Value) = 0 Then
IsCellZero = True
Else
IsCellZero = False
End If
Else
' Value is blank, text or boolean
IsCellZero = False
End If
End Function