如何将我的第三个可见单元格定义为B列中的变量

时间:2019-05-23 11:16:02

标签: excel vba filter

我想在过滤的列B中定义第三个可见单元格的变量。
我的第三个可见单元格的位置可以根据在过滤器中选择的值而变化。

enter image description here

在我的示例中,第三个单元格是B16,但并非总是此值。如果我设法在B列中定义了第三个可见单元格的变量,则可以通过该变量在VBA代码中更改B16。

Sub jfdjdgfjg()
    Dim LastRow As Long
    LastRow = ActiveSheet.Range("B" & Rows.Count).End(xlUp).Row
    ActiveCell.Formula = "= SUM(B16:B" & LastRow & ")" 'Sum until lastrow
End Sub

2 个答案:

答案 0 :(得分:1)

这是一种方法

Option Explicit

Sub thirdviscell()
Dim LRow As Long, i As Long, counter As Long
Dim thirdcell As Range

With ThisWorkbook.Sheets(1)
    LRow = .Cells(.Rows.Count, "A").End(xlUp).Row

    For i = 2 To LRow 'assuming a header row not to be counted
        If .Rows(i).EntireRow.Hidden = False Then counter = counter + 1
        If counter = 3 Then 
            Set thirdcell = .Cells(i, "B")
            Exit For
        End If
    Next i
End With

MsgBox "The third visible cell's address is " & thirdcell.Address(0,0), vbInformation

End Sub

答案 1 :(得分:1)

您可以遍历可见的单元格并像这样对它们进行计数:

Option Explicit

Private Sub Example()
    MsgBox GetFilteredRowNumber(ActiveSheet.Range("B:B"), 3)
End Sub

Private Function GetFilteredRowNumber(ByRef r As Range, ByRef num As Long) As Long
    Dim aCell As Range, i As Long
    GetFilteredRowNumber = 0
    For Each aCell In Intersect(r.Parent.UsedRange, r.SpecialCells(xlCellTypeVisible)).Cells
        i = i + 1
        If i = num Then
            GetFilteredRowNumber = aCell.Row
            Exit For
        End If
    Next aCell
End Function