根据Excel中的下拉列表选择显示/隐藏列

时间:2013-10-18 08:21:53

标签: excel excel-vba vba

我正在尝试根据我的下拉列表选项显示隐藏列。对于单行它可以正常工作,但是当我想扩展我的范围10行

If Range("$CF$5: $CF$15") = "Others" Then

Tt显示Runtime error 13.

以下是我的代码。谢谢你帮助我。

If Range("$CF$5") = "Others" Then
    ActiveSheet.Columns("CG").EntireColumn.Hidden = False
Else
    ActiveSheet.Columns("CG").EntireColumn.Hidden = True
End If 

2 个答案:

答案 0 :(得分:2)

您无法比较范围内的值,就像您正在做的那样。

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

答案 1 :(得分:0)

这个怎么样?这假设如果范围中的单个单元格设置为“其他”,则将显示CG列,如果没有,则将隐藏CG。不确定这是不是你真正想要的?

Dim cell As Range

For Each cell In Range("$CF$5:$CF$15")

    If cell = "Others" Then
        ActiveSheet.Columns("CG").EntireColumn.Hidden = False
        Exit For
    Else
        ActiveSheet.Columns("CG").EntireColumn.Hidden = True
    End If

Next cell