使用Range.CurrentRegion property以隔离数据从A1辐射出的“岛”是限制“范围”的简便方法的操作。您不想将数千个空白单元格复制到数组中。
Sub SWAPS101()
'red color
' If "Security Type" = SW
' If "New Position Ind" = N
' If "Prior Price" = 100
' If "Current Price" does not equal 100
Dim a As Long, r As Long, c As Long, vVALs As Variant
With Sheets("Output")
'reset the environment
If .AutoFilterMode Then .AutoFilterMode = False
.Columns(5).Interior.Pattern = xlNone
With .Cells(1, 1).CurrentRegion
ReDim vVALs(1 To .Columns.Count, 1 To 1)
.AutoFilter field:=Application.Match("security type", .Rows(1), 0), Criteria1:="SW"
.AutoFilter field:=Application.Match("new position ind", .Rows(1), 0), Criteria1:="N"
.AutoFilter field:=Application.Match("prior price", .Rows(1), 0), Criteria1:=100
.AutoFilter field:=Application.Match("current price", .Rows(1), 0), Criteria1:="<>" & 100
With .Resize(.Rows.Count - 1, .Columns.Count).Offset(1, 0)
'check to ensure that there is something to work with
If CBool(Application.Subtotal(103, .Cells)) Then
With Intersect(.Columns(5), .SpecialCells(xlCellTypeVisible))
.Cells.Interior.Color = vbRed
End With
Debug.Print .SpecialCells(xlCellTypeVisible).Areas.Count
With .SpecialCells(xlCellTypeVisible)
For a = 1 To .Areas.Count
Debug.Print .Areas(a).Rows.Count
For r = 1 To .Areas(a).Rows.Count
Debug.Print .Areas(a).Rows(r).Address(0, 0)
ReDim Preserve vVALs(1 To UBound(vVALs, 1), 1 To UBound(vVALs, 2) + 1)
For c = 1 To .Columns.Count
vVALs(c, UBound(vVALs, 2)) = _
.Areas(a).Rows(r).Cells(1, c).Value
Next c
Next r
Next a
vVALs = Application.Transpose(vVALs)
End With
'array is populated - do something with it
Debug.Print LBound(vVALs, 1) & ":" & UBound(vVALs, 1)
Debug.Print LBound(vVALs, 2) & ":" & UBound(vVALs, 2)
'this dumps the values starting a couple of rows down
With .Cells(.Rows.Count, 1).Offset(3, 0)
.Resize(UBound(vVALs, 1), UBound(vVALs, 2)) = vVALs
End With
End If
End With
End With
If .AutoFilterMode Then .AutoFilterMode = False
End With
End Sub
我留下了很多让您可以观看的过程中如何遍历每个Range.Areas property的Range.SpecialCells method的xlCellTypeVisible集中的行debug.print语句。使用F8在浏览VBE的立即窗口([Ctrl] + G)的同时单步执行代码。
后处理结果
你有没有考虑在过滤和vbRed添加可见单元格? – Jeeped
您需要在开始处设置数组的大小,或者执行'ReDim Preserve'来添加满足条件的每个元素。另外,你是否真的想添加*整行*或只是数据行中的单元格? –
@ScottHoltzman - 带有Preserve的[ReDim语句](https://msdn.microsoft.com/en-us/library/w8k3cys2.aspx)是要走的路,但OP将不得不观察哪个** Rank **他/她正在扩大。逐行通常意味着行在第一排和第二排。您只能使用Preserve扩展第二个等级;不是第一个(只扩展*最后*排名)。 'Application.Transpose'可能会有帮助,但也可能会遇到限制([VBA Excel“错误13:类型不匹配”](http://stackoverflow.com/questions/31400105/vba-excel-error-13-type-mismatch) )。 – Jeeped