如何使用vba在Excel 2007中一次隐藏多个列

时间:2017-01-23 13:10:46

标签: excel-vba hide vba excel

我想在Excel工作表中隐藏多个列。这可以很好地使用:

ActiveSheet.Range(“R10:CO10”)。EntireColumn.Hidden = True

“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天的列,我找不到任何关于使用变量或列标识符或列号等隐藏多个列的提示。 / p>

变量的使用最终会在运行时错误1004中结束。

2 个答案:

答案 0 :(得分: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)

答案 1 :(得分:0)

我已经测试了Scotts解决方案的方法,并最终实现了它。在这种情况下,其他人会遇到同样的问题,找到一个有效的解决方案,这是我的解决方案:

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