[英]How To Number In Sequence Only Visible Rows In Excel Using VBA?
目標是讓我的代碼僅按順序排列可見行,以便如果應用過濾器或刪除行,最終用戶可以單擊“刷新”按鈕,如下圖所示,更新序列和摘要頁面頂部。
我目前使用的代碼適用於該范圍內的所有單元格,包括隱藏的單元格,我不知道如何更改它以使其僅適用於可見單元格。
這是附加到我的“刷新”按鈕的代碼;
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
提前致謝!
這是未經測試的,因此請在您的數據副本上嘗試一下,我還假設您想將編號放在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
這將基本上遍歷所有行,檢查它們是否可見,如果是,則插入行計數器
處理 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.