2015-01-09 1662 views
0

我不想問這個,因爲我確實有一個解決方法,但我更喜歡一個更清晰的答案。Excel VBA:隱藏所有列,然後取消隱藏某些列

我使用的是Excel 2010,我有一個在新工作表上執行一些基本格式設置的過程:隱藏所有列,設置標題行文本,設置標題行格式,取消隱藏標題行使用的列。問題是取消隱藏不起作用。該過程運行後,工作表看起來像所有的列仍然隱藏,但如果我調整公式欄,程序unhid列出現我所期望的列。即使在保存,關閉並重新打開工作簿時,只有在調整公式欄的大小時才顯示這些列。

我試着用DoEvents來刷新屏幕。儘管我從未將它設置爲false,但我試圖將Application.ScreenUpdating設置爲true。我甚至試圖通過VBA隱藏和取消隱藏配方欄。唯一可行的(我的解決方法)是將公式欄作爲過程的一部分調整大小。它確實有效,但似乎不應該有必要。在取消隱藏之前,它可能會激活範圍,但我不想在VBA中使用ActivateSelect

有什麼想法?

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 
+0

這有一個微軟的bug環。 – theMayer 2015-01-10 16:49:49

回答

0

LASTCOL =範圍( 「A1」)。完(xlToRight).COLUMN

與SH

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

結束隨着

+0

我把這個標記爲答案,儘管我對隱藏線使用了稍微不同的形式:'Header.Offset(,EndCol).Resize(,LastCol - EndCol).Columns.Hidden = True'。謝謝! – phrebh 2015-01-12 14:21:58

1

如果你希望它取消隱藏所有單元格:

cells.EntireColumn.Hidden = False 

如果你只是想取消隱藏在標題中使用的5列,那麼:

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

這隻會取消隱藏「標題」中的列,並且它必須放在With語句之外才能工作(將其作爲最後一行)。它使用。選擇,我知道,但是這就是我能得到它的工作的唯一辦法....

0

下面將隱藏所有列然後選擇性地取消隱藏。

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

這僅適用於列

worksheet.Cells.EntireRow.Hidden = true 

不工作。