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

我毫不犹豫地问这个,因为我有一个解决方法,但我更喜欢一个更清晰的答案。

我正在使用Excel 2010,我有一个过程,在新工作表上做一些基本的格式化:隐藏所有列,设置标题行文本,格式化标题行,取消隐藏标题行使用的列。 问题是取消隐藏不起作用。 该过程运行后,工作表看起来像所有的列仍然隐藏,但如果我调整公式栏,过程unhid列出现我所期望的。 即使在工作簿被保存,closures并重新打开时,只有在调整公式栏的大小时才显示这些列。

我尝试使用DoEvents来刷新屏幕。 我试图设置Application.ScreenUpdating为true,即使我从来没有把它设置为false。 我甚至试图通过VBA隐藏和取消隐藏配方栏。 唯一的作品(我的解决方法)是作为过程的一部分调整公式栏。 它确实有效,但似乎不应该是必要的。 在取消隐藏之前,它可能会激活范围,但我不想在VBA中使用“ Activate或“ Select

有什么想法吗?

 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 

LastCol = Range(“A1”)。End(xlToRight).Column

用sh

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

结束

如果你想要取消隐藏所有单元格:

 cells.EntireColumn.Hidden = False 

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

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

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

以下将隐藏所有列,然后select性地取消隐藏。

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

注意这只适用于列

 worksheet.Cells.EntireRow.Hidden = true 

不起作用。