Excel VBA循环显示可见的已过滤行

时间:2015-10-21 01:37:05

标签: vba loops rows visible

我有一个带自动过滤器的excel表。

在过滤后的表中,我只过滤了几行。

我的目标是icterate所有可见行,以收集数据以复制到另一张表。

我想要一种方法来收集带有fisrt可见行号的变量。

我的草案代码是:

Dim cnp As String
Dim nome As String
Dim filter_rng As Range
Dim rw As Range
Dim last_row As Long 'last visible data row
Dim dest_row As Long 'row to paste the colected data

Set filter_rng = Range("A5:Y" & last_row).Rows.SpecialCells(xlCellTypeVisible)
'collect data
For Each rw In filter_rng.SpecialCells(xlCellTypeVisible)
    workshett(1).Activate
    cnp = Range("a" & rw).Value
    nome = Range("b" & rw).Value

'copy data to another worksheet first data line is cell A2
    Worksheet(2).Activate
    Range("A" & dest_row + 1).Value = cnp
    Range("b" & dest_row + 1).Value = nome

Next rw

1 个答案:

答案 0 :(得分:8)

GD Joao,

您的代码包含多个错误,并且您提供的其他信息很少,无法让我们为您提供帮助,但需要尝试。

请参阅以下代码并与您的代码进行比较,以下代码与您尝试执行的操作最接近,并经过测试和运行。

Dim cnp As String
Dim nome As String
Dim filter_rng As Range
Dim rw As Range
Dim last_row As Long 'last visible data row
Dim dest_row As Long 'row to paste the colected data

last_row = 200
dest_row = 1

Set filter_rng = Sheets(1).Range("A5:Y" & last_row)

'collect data
For Each rw In filter_rng.SpecialCells(xlCellTypeVisible)
    'Worksheets(1).Activate
    cnp = Sheets(1).Range("A" & rw.Row).Value
    nome = Sheets(1).Range("B" & rw.Row).Value

'copy data to another worksheet first data line is cell A2
    'Worksheets(2).Activate
    Sheets(2).Range("A" & dest_row + 1).Value = cnp
    Sheets(2).Range("B" & dest_row + 1).Value = nome

Next rw
祝你好运!