如何使用VBA在Excel中仅按顺序对可见行进行编号?

时间:2018-10-17 21:34:48

标签: excel vba

目标是让我的代码仅按顺序显示可见行,以便如果应用过滤器或删除行,最终用户可以单击“刷新”按钮(如下图所示),以更新序列和页面顶部的摘要。

我目前使用的代码适用于范围中的所有单元格,包括隐藏的那些单元格,我不知道如何更改它,使其仅适用于可见单元格。

This is the Report

这是我的“刷新”按钮上附带的代码;

Private Sub Refresh_Click()

Application.Goto Reference:="R10C2"
Selection.End(xlDown).Select

Dim maxRowIndex As Long
Dim rowCounter As Long

maxRowIndex = ActiveCell.Row - 9
rowCounter = 1

Range("A10").Select

For rowCounter = 1 To maxRowIndex
ActiveCell = rowCounter
ActiveCell.Offset(1).Select
Next

End Sub

谢谢!

3 个答案:

答案 0 :(得分:1)

这是未经测试的,因此请在您的数据副本上进行尝试,我还假设您希望将编号放在A列中:

Private Sub Refresh_Click()

Dim totalRows As Long
Dim rowCounter As Long
Dim i as long

rowCounter = 1
totalRows = ActiveSheet.UsedRange.Rows.Count + ActiveSheet.UsedRange.Row - 1    

for i = 10 to totalRows
    If ActiveSheet.Rows(i).Hidden = False then 
        Range("A" & i).Value = rowCounter 
        rowCounter = rowCounter + 1
    End if  
Next i

End Sub

这基本上将遍历所有行,检查它们是否可见,如果是,则插入行计数器

答案 1 :(得分:0)

浏览SpecialCells(xlCellTypeVisible)中的单元格。

Option Explicit

Private Sub Refresh_Click()

    Dim a As Long, n As Long, r As Range

    If CBool(Application.Subtotal(103, Range(Cells(10, "B"), Cells(Rows.Count, "B")))) Then
        Range(Cells(10, "B"), Cells(Rows.Count, "B").End(xlUp)).Offset(0, -1).ClearContents
        For Each r In Range(Cells(10, "B"), Cells(Rows.Count, "B").End(xlUp)).SpecialCells(xlCellTypeVisible)
            n = n + 1
            r.Offset(0, -1) = n
        Next r
    End If

End Sub

答案 2 :(得分:0)

您不需要VBA仅对可见行进行编号。 WorkSheetFunction小计将为您提供相同的结果。

=SUBTOTAL(3,B$10:B10)

enter image description here