Excel VBA:隐藏所有列,然后取消隐藏某些列

Excel VBA: Hide all columns, then unhide some columns

我犹豫要问这个问题,因为我确实有解决方法,但我希望给出一个更干净的答案。

我正在使用Excel 2010,并且我有一个在新工作表上执行一些基本格式设置的过程:隐藏所有列,设置标题行文本,设置标题行格式,取消隐藏标题行使用的列。问题在于取消隐藏无法正常工作。运行该过程后,工作表看起来像所有列仍处于隐藏状态,但是如果我重新调整编辑栏的大小,则取消隐藏该过程的列会像我期望的那样出现。即使在保存,关闭并重新打开工作簿后,这些列也不会出现,直到我调整了公式栏的大小。

我尝试使用DoEvents刷新屏幕。我尝试将Application.ScreenUpdating设置为true,即使我从未将其设置为false。我什至尝试通过VBA隐藏和取消隐藏公式栏。唯一有效的方法(我的解决方法)是在过程中调整公式栏的大小。它确实有效,但是似乎没有必要。在取消隐藏之前,可以激活该范围,但是我不希望在VBA中不使用ActivateSelect

有什么想法吗?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
Private Sub FormatSheet(sh As Worksheet)
    Dim HeaderText As Variant
    Dim EndCol As Long
    Dim Header As Range

    'header items for sheet
    HeaderText = Array("DATE","USER","BC","TC","SUM")

    'get last column index based on headers
    EndCol = UBound(HeaderText) - LBound(HeaderText) + 1

    With sh
        'hide all columns in the sheet
        .Columns.Hidden = True

        'set the header range
        Set Header = .Range(.Cells(2, 1), .Cells(2, EndCol))

        'set the header text
        Header = HeaderText

        'set the header row formatting
        With .Rows(2)
            .Font.Bold = True
            .Interior.Color = RGB(217, 217, 217)
            With .Borders(xlEdgeBottom)
                .LineStyle = xlContinuous
                .Weight = xlThin
            End With
        End With

        'unhide the columns used by the header
        Header.EntireColumn.Hidden = False

        'resize the formula bar to force the unhide to work
        Application.FormulaBarHeight = 5
        Application.FormulaBarHeight = 1

        'autofit columns
        .Columns.AutoFit
    End With
End Sub


如果要取消隐藏所有单元格,请执行以下操作:

1
cells.EntireColumn.Hidden = False

而且,如果您只想取消隐藏标题中使用的5列,则:

1
Range(Cells(1, 1), Cells(1, EndCol)).EntireColumn.Select

这只会取消隐藏" Header"内的列,并且必须将其放在With语句之外才能起作用(将其作为最后一行)。 我知道,它使用.select,但这就是我可以使用它的唯一方法。


下面将隐藏所有列,然后有选择地取消隐藏。

1
2
3
worksheet.Cells.EntireColumn.Hidden = true
worksheet.Cells(1,1).EntireColumn.Hidden = false
worksheet.Cells(1,2).EntireColumn.Hidden = false

注意这仅适用于列

1
worksheet.Cells.EntireRow.Hidden = true

不起作用。


LastCol = Range(" A1")。End(xlToRight).Column

与sh

1
.Cells(1, EndCol + 1).Resize(, LastCol - EndCol).Columns.Hidden = True

结束于