[英]SpecialCells(xlCellTypeVisible) also includes hidden/filtered cells
I have a dataset that I'm using a filter on. 我有一个使用过滤器的数据集。 I simply want to calculate the total values in column N, that are visible.
我只是想计算可见的N列中的总值。 The data starts in row 2, and ends at row 2047.
数据从第2行开始,到第2047行结束。
I saw this thread but it gives me the same type of issue I'm having. 我看到了这个线程,但是它给了我同样的问题。
Here's my function: 这是我的功能:
Function sumVisible() As String
Dim rng As Range
Set rng = Range("N2:N2047").SpecialCells(xlCellTypeVisible)
' Debug.Print "Range: " & rng.Address & ", Sum: " & WorksheetFunction.Sum(rng)
sumVisible = Format(WorksheetFunction.Sum(rng), "$#,###.##")
End Function
With my current filter, my header row (1) is visible, as are rows 901 to 937. So, I want to sum N901:N937. 使用我当前的过滤器,我的标题行(1)可见,行901到937也可见。因此,我想对N901:N937求和。
However, the rng
keeps getting set to $N$2:$N$2047
. 但是,
rng
一直设置为$N$2:$N$2047
。 I expected it to be $N$901:$N$937
. 我希望它是
$N$901:$N$937
。
Using the function that is given to the thread I linked to above, I get a range of $N$2:$N$937
...so at the very least, I'm getting the end row correctly, but not the start row. 使用上面链接到的线程的函数,我得到了
$N$2:$N$937
……因此至少,我正确地获得了结束行,但没有获得开始行。
But! 但! if I type
Range("N2:N2047").SpecialCells(xlCellTypeVisible).Select
in the Immediate Window, outside of a macro, it correctly selects just the visible cells. 如果我键入
Range("N2:N2047").SpecialCells(xlCellTypeVisible).Select
。在立即窗口中在宏外部选择,它会正确地只选择可见的单元格。 And one step further, doing ?Range("N2:N2047").SpecialCells(xlCellTypeVisible).address
correctly returns $N$901:$N$937
. 再进一步,执行
?Range("N2:N2047").SpecialCells(xlCellTypeVisible).address
正确返回$N$901:$N$937
。
What may be going wrong? 可能出什么问题了?
Edit: I just found that doing =SUBTOTAL(9,N1:N2047)
will just sum the visible cells, so I'm using that. 编辑:我只是发现做
=SUBTOTAL(9,N1:N2047)
只会合计可见单元格,所以我正在使用它。 But my question still stands - why isn't SpecialCells(xlCellTypeVisible)
working correctly in the macro? 但是我的问题仍然存在-为什么
SpecialCells(xlCellTypeVisible)
在宏中不能正常工作?
Try setting your rng
with the line below: 尝试使用以下行设置
rng
:
Set rng = Range("N2:N" & Cells(Rows.Count, "N").End(xlUp).Row).SpecialCells(xlCellTypeVisible)
Later using your debug line Debug.Print rng.Address
, I get the following range in the immediate window: 稍后使用您的调试行
Debug.Print rng.Address
,我在即时窗口中得到以下范围:
$N$901:$N$937
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.