你不能像你正在做的那样比较范围内的值。
If Range("$CF$5: $CF$15") = "Others"
有很多方法可以进行比较。循环遍历范围是最常见的方式。下面是另一种检查垂直范围内的所有单元格是否具有相同值的方法。
这是你正在尝试的吗?
Sub Sample()
Dim ws As Worksheet
Dim rng As Range
'~~> Set your worksheet here
Set ws = ThisWorkbook.Sheets("Sheet1")
With ws
'~~> Set your range here
Set rng = .Range("CF5:CF15")
'~~> Check if any cell in the range have "Others"
If Application.WorksheetFunction.CountIf(rng, "Others") = _
rng.Rows.Count Then
.Columns("CG").EntireColumn.Hidden = False
Else
.Columns("CG").EntireColumn.Hidden = True
End If
End With
End Sub
编辑:
如果你想显示/隐藏列,即使有一个“其他”的实例,那么你也不需要循环。看这个
Sub Sample()
Dim ws As Worksheet
Dim rng As Range
'~~> Set your worksheet here
Set ws = ThisWorkbook.Sheets("Sheet1")
With ws
'~~> Set your range here
Set rng = .Range("CF5:CF15")
'~~> Check if all the cells in the range have "Others"
If Application.WorksheetFunction.CountIf(rng, "Others") > 0 Then
.Columns("CG").EntireColumn.Hidden = False
Else
.Columns("CG").EntireColumn.Hidden = True
End If
End With
End Sub