使用vba查看和隐藏excel中的列

时间:2014-05-24 11:32:41

标签: excel excel-vba vba

我有一个工作表,其中包含B列中的值:G。在单元格A1的同一张表格中,我使用数据验证制作了一个下拉列表,其中包含A,B和C等值。

我需要的是当我选择单元格值A时,列B:C需要可见,其他列应该从D:G隐藏。同样地,如果我从列表中选择B,我需要查看列D:E和B:C和F:G应该被隐藏。

请你帮我解决一下。

注意:我对VBA不了解。

3 个答案:

答案 0 :(得分:5)

试试这个:

  1. 打开VBA编辑器(ALT + F11
  2. 双击Sheet1
  3. 选择左上角的Worksheet下拉列表,右上角的Change下拉列表
  4. 粘贴此代码
  5. NB-这假设数据验证在单元格A1

    Private Sub Worksheet_Change(ByVal Target As Range)
        Dim allColumns As Range
    
        Set allColumns = Columns("B:G")
        allColumns.Hidden = True
    
        If Not Intersect(Target, Range("A1")) Is Nothing Then
            If Target.Value = "A" Then
                Columns("B:C").Hidden = False
            ElseIf Target.Value = "B" Then
                Columns("D:E").Hidden = False
            ElseIf Target.Value = "C" Then
                //Add more logic here
            End If
        End If
    End Sub
    

答案 1 :(得分:3)

转到视图 - >宏。
点击下拉列表,然后记录新宏"。 右键单击列标题并隐藏列 然后取消隐藏列。 做宏 - >停止录制。 宏 - >查看宏 点击编辑。

您将获得以下代码:

Columns("C:C").Select
Selection.EntireColumn.Hidden = True
Selection.EntireColumn.Hidden = False

现在您知道如何隐藏和显示列。首先选择列然后设置Hidden = true或false。

Google:当单元格值更改时,excel宏

点击第一个链接:http://support.microsoft.com/kb/213612

从该链接获取代码并阅读评论:

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim KeyCells As Range

    ' The variable KeyCells contains the cells that will
    ' cause an alert when they are changed.
    Set KeyCells = Range("A1:C10")

    If Not Application.Intersect(KeyCells, Range(Target.Address)) _
           Is Nothing Then

        ' Display a message when one of the designated cells has been 
        ' changed.
        ' Place your code here.
        MsgBox "Cell " & Target.Address & " has changed."

    End If
End Sub

请务必仔细阅读相关链接。并按照说明操作。我发现有时候我会匆忙而错过重要的细节

请告诉我这是否足够,或者您需要更多帮助。

答案 2 :(得分:0)

已经很长时间了,但它可能仍然对某人有用。 隐藏-取消隐藏工作表列的用户表单:

我们创建的用于隐藏工作簿中的列和取消隐藏隐藏列的用户表单还包含一个用于最小化用户表单的按钮。用户表单中的下拉列表可以在工作表之间导航,从组合框中选择的工作表处于活动状态,并提供该工作表的列管理(隐藏-取消隐藏)。

enter image description here

Explanations and sample Excel file here