如何在Excel中访问过滤范围之外的单元格内容?

时间:2012-08-17 17:31:50

标签: excel vba

此代码将通过过滤范围并仅将可见单元格插入到数组中(假设列A已根据我的条件进行过滤)。但是,我真正想做的是将一列翻过来并插入" B3"进入我的阵列而不是" A3"。如何修改我的代码?

For Each cell In Range.SpecialCells(xlCellTypeVisible)
    Array1(i) = cell.Value
    i = i + 1
Next c

我在想像Array1(i)= Cells(cell.Row,cell.Column + 1).Value

3 个答案:

答案 0 :(得分:1)

For Each cell In Range.SpecialCells(xlCellTypeVisible)
    Array1(i) = cell.Offset(ColumnOffset:=1).Value
    i = i + 1
Next c

答案 1 :(得分:1)

For Each cell In Range.SpecialCells(xlCellTypeVisible)
   Array1(i) = cell.Offset(0, 1).Value
   i = i + 1

Next c

答案 2 :(得分:1)

由于B列将与A列相同,因此这里有一个灵活的解决方案,允许您指定要使用的列:

Sub FilterColumn(ColumnNumber As Long)
Dim LastRow As Long
Dim rng As Range
Dim rngVisible As Range
Dim cell As Range
Dim Array1() As Variant
Dim i As Long

With ActiveSheet
    Set rng = .Columns(ColumnNumber)
    LastRow = .Cells(.Rows.Count, ColumnNumber).End(xlUp).Row
    On Error Resume Next
    Set rngVisible = .Range(.Cells(2, ColumnNumber), .Cells(LastRow, ColumnNumber)).SpecialCells(xlCellTypeVisible)
    On Error GoTo 0
    If Not rngVisible Is Nothing Then
        ReDim Preserve Array1(1 To rngVisible.Cells.Count)
        i = 1
        For Each cell In rngVisible
            Array1(i) = cell.Value
            i = i + 1
        Next cell
    End If
End With
End Sub

对于B栏这样称呼它:

FilterColumn 2

作为旁注,我建议你不要将Excel保留字用于变量名。范围是保留字。