VBA使用xlFillSeries自动填充可见单元格(过滤范围)

时间:2012-01-27 17:17:57

标签: excel vba filter excel-vba

我想将2..N整数序列填充到过滤/可见范围内。

此代码填写了该系列,但忽略了过滤范围:

COL_SID_CURRENT = 3
COL_SID_CURRENT_STR = "c"
ROW_LAST = ActiveSheet.UsedRange.Rows.Count

' Start the series with value 2 in cell "c2"
Cells(2, COL_SID_CURRENT).FormulaR1C1 = "2"

aRangeStr = "" & COL_SID_CURRENT_STR & "2"      ' -> "c2"
Range(aRangeStr).Select

aRangeStr = aRangeStr & ":" & COL_SID_CURRENT_STR & ROW_LAST      ' -> "c2:c24"
Selection.AutoFill Destination:=Range(aRangeStr),Type:=xlFillSeries 

我尝试将xlCellTypeVisible添加到代码中,但我的所有组合都没有工作:

Range(aRangeStr).SpecialCells(xlCellTypeVisible).Select
Selection.AutoFill Destination:=Range(aRangeStr).SpecialCells(xlCellTypeVisible), _
   Type:=xlFillSeries 

任何提示如何仅在过滤/可见细胞上填充系列?

1 个答案:

答案 0 :(得分:1)

自动填充功能不适用于过滤范围,但可以选择。 :)

已经过测试

您可以使用此公式(我假设您根据Col A中存储的内容进行过滤(参见示例图像)

我在单元格“c2”

中以值2开始系列时添加+ 1
=IF(A2="FILTER_TEXT",COUNTIF($A$2:A2,"FILTER_TEXT")+1,"")

enter image description here

要使其适应您的示例,请使用此代码。

Sub Sample()
    COL_SID_CURRENT = 3
    COL_SID_CURRENT_STR = "c"

    ROW_LAST = ActiveSheet.UsedRange.Rows.Count

    ' Start the series with value 2 in cell "c2"
    Cells(2, COL_SID_CURRENT).Formula = "=IF(A2=""FILTER_TEXT"",COUNTIF($A$2:A2,""FILTER_TEXT"")+1,"""")"

    aRangeStr = "" & COL_SID_CURRENT_STR & "2"      ' -> "c2"

    aRangeStr = aRangeStr & ":" & COL_SID_CURRENT_STR & ROW_LAST      ' -> "c2:c24"
    Range(aRangeStr).Formula = "=IF(A2=""FILTER_TEXT"",COUNTIF($A$2:A2,""FILTER_TEXT"")+1,"""")"
End Sub

请将“FILTER_TEXT”更改为相关文字。您也可能需要更改参考范围。就像我提到的那样,我假设过滤器是基于Col A中的值。