VBA筛选结果行数错误

语言:Excel VBA

scheme:我有一个源范围(rngDTRef_AllRecord),我需要将数据插入目标范围(rngRTDC_AllDetail)

对于源范围(rngDTRef_AllRecord)中的每一行(rngCurrRow),它都会过滤目标范围(rngRTDC_AllDetail)

如果filter产出结果,则会将一些数据添加到结果行(注意:每个结果都是唯一的)

否则它会将新行添加到目标范围(rngRTDC_AllDetail)

下面是代码:

For Each rngCurrRow In rngDTRef_AllRecord.Rows intRTDC_RowBegin = 7 intRTDC_ColIdxTotal = 20 intRTDC_RowLast = fntGetNewLastRow 'this is some function get last row of rngRTDC_AllDetail due to might add in new row Set rngRTDC_AllDetail = shtRTDC.Range(shtRTDC.Cells(intRTDC_RowBegin, 1), shtRTDC.Cells(intRTDC_RowLast, intRTDC_ColIdxTotal)) rngRTDC_AllDetail.AutoFilter rngRTDC_AllDetail.AutoFilter Field:=intRTDC_ColIdxAcc, Criteria1:=rngCurrRow.Cells(1, intDTSource_ColIdxAccCode), Operator:=xlAnd rngRTDC_AllDetail.AutoFilter Field:=intRTDC_ColIdxText, Criteria1:=rngCurrRow.Cells(1, strCurrAccCodeText), Operator:=xlAnd Dim rngResult As Range Set rngResult = rngRTDC_AllDetail.rows.SpecialCells(xlCellTypeVisible)'rngRTDC_AllDetail.SpecialCells(xlCellTypeVisible) also not work 'after filter, it will be only 1 result or none If (rngResult.Rows.Count > 0) Then 'if the filter have result, do something here. else 'add new row End If Next 

我的问题是filter后,从Excel工作表,我可以看到,只有1条logging,但rngResult.Rows.Count = 2'为rngRTDC_AllDetail第一个filterlogging(只有1行),我怀疑由于它包括头,但我不知道什么是错的。

rngResult.Rows.Count = 1'表示剩余的有1行的filterlogging

更糟糕的是当filter没有logging时,rngResult.Rows.Count = 1

任何意见将不胜感激。 TQ。

好。 花了一些时间后,我已经find了解决scheme。 以下是面对类似问题的人的一些注意事项。

目标:当columnA =“a”AND columnB =“b”时,要将“值”插入到columnC中,并且该行仅在1到10之间

  ABC 1 columnA | columnB | ColumnC 2 a | b | value 3 a | x | 4 x | x | 5 x | x | 6 c | b | 7 a | b | value 8 x | x | 9 x | x | 10 a | b | value 11 a | b | 12 a | b | ... 'insert value at columnC ActiveSheet.Range("A1:B10").AutoFilter Field:=1, Criteria1:="a", Operator:=xlAnd ActiveSheet.Range("A1:B10").AutoFilter Field:=2, Criteria1:="b", Operator:=xlAnd Dim rng As Range For Each rng In ActiveSheet.AutoFilter.Range.Range("A1:B10").SpecialCells(xlCellTypeVisible).Rows If (rng.Row <> 1) Then 'no the header ActiveSheet.Cells(rng.Row, "c") = "value" 'set value at C2,C7,C10 End If Next rng 'count the total row visible Dim rngA As Range Set rngA = ActiveSheet.AutoFilter.Range.Range("A1:B10") Debug.Print rngA.Columns(1).SpecialCells(xlCellTypeVisible).Count - 1 'result 3 'Reference:http://www.contextures.com/xlautofilter03.html 

Note1 **:“ActiveSheet.AutoFilter.Range”将始终包含标题和所有下面的行作为可见行。

Note2 **:“ActiveSheet.AutoFilter.Range.Offset(1,0).SpecialCells(xlCellTypeVisible).Rows”将仅偏移下面的1行,如果需要设置结果行的值,则不适用。