2017-01-23 109 views
1

我想隱藏Excel工作表中的多列。如何在Excel 2007中一次使用vba隱藏多列

ActiveSheet.Range:該作品採用精緻漂亮。( 「R10:CO10」)EntireColumn.Hidden =真

「R10」 是隱藏在第一和修復列。第二列和隱藏之間的所有列將根據日期值動態確定。

樣品編碼:

Private Sub Worksheet_Activate() 
    Dim c As Range 
    Dim start As String 
    Dim ende As String 
    start = "R10" 
    ende = "CO10" 
    Dim d As Date 
    d = Date 
    For Each c In Range("R10:HU10") 
     If c = (d - 8) Then 
      ende = **how to assign???** 
     End If 
     If c = (d - 7) Then 
      Application.Goto c, True 
     End If 
    Next c 
    'ActiveSheet.Range(**"start:ende"**).EntireColumn.Hidden = True 
End Sub 

行10日舉行的價值觀和我想隱藏哪個日期是7天以上的所有列和我不能找到隱藏使用變量或具有多個列的任何提示列標識符或正如Scott指出,使用變量在運行時錯誤1004

+0

只是躲你去通過循環:'c.EntireColumn.Hidden = C <(d -7)'代替你的整個if語句。 –

+0

易於實現,它工作正常,但屏幕閃爍,同時按順序隱藏每列。這就是爲什麼我想立即隱藏一系列列的原因 –

+0

然後關閉屏幕更新。在子的開始部署'Application.ScreenUpdating = False',結尾部署Application.ScreenUpdating = True。 –

回答

0

最終列等

的數量,我的第一個答案是不完整的。您可以使用以下功能:

Function GetColChars(col As Integer) As String 

    Dim coldown As Integer 'Column Countdown 
    Dim colrem As Integer 'Coumn Value Remaining 
    Dim colname As String 'Temporary String value for column name 

    Const alphanums = 26 
    Const aposition = 64 
    coldown = col 
    colname = "" 

    While coldown > 0 

     colrem = coldown Mod alphanums 
     If colrem = 0 Then colrem = 26 
     newchar = Chr(64 + colrem) 
     colname = newchar & colname 
     coldown = Int((coldown - 1)/alphanums) 

    Wend 

    GetColChars = colname 

End Function 

然後調用函數來獲取列字母:

ende = GetColChars(c.column) 
+0

你好,明天我會試試你的解決方案。非常感謝你。 –

0

我測試斯科茨解決方法,並終於得到了它的工作。在其他一些人會用同樣的問題鬥爭,得到一個有效的解決方案的話,這裏是我的解決方案:

Private Sub Worksheet_Activate() 

Dim lastDateRangeColumn As Range 
Dim givenDateRange As Range 
Set givenDateRange = ActiveSheet.Range("R10:HU10") 
Dim firstDateRangeColumn As Range 
Set firstDateRangeColumn = ActiveSheet.Range("R10") 

Dim todaysDate As Date: todaysDate = Date 

For Each tempDateRangeColumn In givenDateRange 
    If tempDateRangeColumn < (todaysDate - 7) Then 
     Set lastDateRangeColumn = ActiveSheet.Range(tempDateRangeColumn.Address) 
    End If 
    If tempDateRangeColumn = (todaysDate - 7) Then 
     Application.Goto tempDateRangeColumn, True 
    End If 
Next tempDateRangeColumn 

Dim firstColumnNumber As Long 
Dim lastColumnNumber As Long 
firstColumnNumber = Range(firstDateRangeColumn.Address).Column 
lastColumnNumber = Range(lastDateRangeColumn.Address).Column 

Dim rangeToBeHidden As Range 
Set rangeToBeHidden = Range(Cells(1, firstColumnNumber), Cells(1, lastColumnNumber)) 

rangeToBeHidden.EntireColumn.Hidden = True 

End Sub