与Lastrow不起作用的FormulaArray

时间:2016-02-20 18:08:12

标签: excel-vba vba excel

我正在尝试使用公式从单元格D中的1个数字到下一个1之前的数据计数,但是我能够使用公式得到它

Index   Level   Header  Test
3        3       ADD    1
4        4       AAC    
5        5       AAG    
6        3       ASC    1
7        4       AIA    
9        4       ABB    1
10       5       APP    
12       5       BBS    1
13       6       SST    
3        3       AIUH   1
4        4       AAC    
5        5       AAG    
6        3      The ASC 1
7        4      AIA 
9        4      ABB Inc 1
10       5      APP 
12       5      BBS     1
13       6      SST 
3        3      AIUH    1
4        4      AAC 
5        5      AAG 
6        3      ASC     1
7        4      AIA 
9        4      ABB     1
10       5      APP 
12       5      BBS     1
13       6      SST 

单元格G2,值为1,供参考

"=SMALL(IF($D$2:$D$100=$H$2,ROW($D$2:$D$100)),ROW(D1)+1)-SMALL(IF($D$2:$D$100=$H$2,ROW($D$2:$D$100)),ROW(D1))"

但我无法在vba中使用最后一行& fillarray或filldown也

如果任何专家花一点时间帮助我,

会很有帮助

Sub tes()
Dim LR As Long
LR = Cells(rows.Count, "K").End(xlUp).Row

Sheets("sheet3").Activate
With Sheets("sheet3")
.Range("C1").End(xlDown).Offset(1, 1).Value = 1
.Range("A1").AutoFilter Field:=4, Criteria1:="1"
.Range("C1").Select
.Range(Selection, Selection.End(xlDown)).Copy
.Range("L1").PasteSpecial Paste:=xlPasteAll

If ActiveSheet.AutoFilterMode = True Then ActiveSheet.AutoFilterMode = False
Application.CutCopyMode = False
.Range("H1") = "Value"
.Range("H2") = 1
.Range("M1") = "Count"

'Which is working cell wise
.Range("M2").FormulaArray = "=SMALL(IF($D$2:$D$100=$H$2,ROW($D$2:$D$100)),ROW(D1)+1)-SMALL(IF($D$2:$D$100=$H$2,ROW($D$2:$D$100)),ROW(D1))"


'Trying to fill down using filldown not working
.Range("L1").End(xlDown).Offset(0, 1).Select
.Range(Selection, Selection.End(xlUp)).Select
.Selection.FillDown

'Trying to use lastrow in column with Fillarray which is also not working
.Range("M2:M" & LR).FormulaArray = "=SMALL(IF($D$2:$D$100=$G$2,ROW($D$2:$D$100)),ROW(D1)+1)-SMALL(IF($D$2:$D$100=$G$2,ROW($D$2:$D$100)),ROW(D1))"


End With

End Sub

我甚至尝试过不使用激活或选择,但我不知道如何在没有这些的情况下使用。

非常感谢专家,周末愉快!

我也分享了该链接以供参考enter link description here

1 个答案:

答案 0 :(得分:0)

使用Range.FormulaArray property将公式放入第一个单元格,然后使用Range.FillDown method完成范围的其余部分。

With Worksheets("Sheet3")
    .Range("M2").FormulaArray = _
      "=SMALL(IF($D$2:$D$100=$H$2,ROW($B$2:$D$100)),ROW(1:1)+1)-SMALL(IF($D$2:$D$100=$H$2,ROW($D$2:$D$100)),ROW(1:1))"
    .Range("M2:M" & lr).FillDown
    .Range("N2").FormulaArray = _
      "=SMALL(IF(R2C4:R100C4=R2C8,ROW(R2C2:R100C4)),ROW(R[-1])+1)-SMALL(IF(R2C4:R100C4=R2C8,ROW(R2C4:R100C4)),ROW(R[-1]))"
    .Range("N2:N" & lr).FillDown        
End With

xlA1 xlR1C1 公式语法都适用于.FormulaArray属性,但您需要从单个单元格开始。