对于每个隐藏单元格,在该隐藏单元格的单元格中设置一个值

时间:2013-07-09 06:19:09

标签: vba excel-vba excel

我有一张表(A3-6)根据输入表格(A1)上方单元格的数字取消隐藏行。在行列A3-6中,用户在单元格中选择具有数据变量列表的选项。现在我要做的是每个隐藏的单元格将隐藏单元格中的值设置为默认选项。

Dim i As Long
        For i = 2 To 10
            If (Rows("2:10").Hidden = True) Then
                'Set the default values for the cell?
        End If
        Next i

此代码根据输入A1

中的数字隐藏行
If Target.Address = "$A$1" Then
        Rows("3:6").Hidden = True
        Rows("2:" & 2 + Val(Target.Value)).Hidden = False
    End If 

enter image description here

1 个答案:

答案 0 :(得分:1)

这可能会给你一些想法:

Sub resetHiddenRangeValue()

    Dim rngMyRange As Range, rngVisible As Range, rngCell As Range

    Set rngMyRange = Range("A3:A6")
    Set rngVisible = Range("A3:A6").SpecialCells(xlCellTypeVisible)

    For Each rngCell In rngMyRange
        If Intersect(rngCell, rngVisible) Is Nothing Then
            ' Is the default value rngcell.offset(0,6).value?
            rngCell.Value = "My Default Value" 
        End If
    Next rngCell

End Sub

可以避免循环,但它有点棘手:

Sub resetHiddenRangeValueNoLooping()

    Dim rngMyRange As Range, rngVisible As Range, rngHidden As Range, varVisible As Variant

    Set rngMyRange = Range("A3:A6")
    Set rngVisible = Range("A3:A6").SpecialCells(xlCellTypeVisible)

    ' Trick: store the initial values of the visible range to a variant array
    varVisible = rngVisible.Value

    ' Substitute the contents of rngVisible with something random
    rngVisible.Value = "Blah_Blah_Blah"

    ' Use the Columndifferences method to set the hidden range
    Set rngHidden = rngMyRange.ColumnDifferences(rngVisible(1, 1))

    ' Fill up the range with the default value-can also be an array or range of values
    rngHidden.Value = "My Default Value"

    ' restore the original values of the visible range
    rngVisible.Value = varVisible

End Sub