简体   繁体   中英

Add a sheet counter in a cell

i have a excel file with a lot of sheets. i want to make a sheet counter to put in a specific cell of each one of those sheets "sheet x of Y" for example, if you are on the sheet 3 of 5, in the cell "X5" must to say "sheet 2" and in the cell "X6" say "of 5" each sheet have a button to add other sheet, so the sheet counter must be update every time you add a sheet

i tried this code but doesn't work, it only puts "0" in the first sheet

Public Sub CountWorkSheets()
If Application.Sheets.Count = 2 Then
Sheets(1).Range("X5").Value = 1 And Sheets(2).Range("X5").Value = 2
End If
End Sub

I suggest go to ThisWorkbook and hook into the NewSheet event

scr

Private Sub Workbook_NewSheet(ByVal Sh As Object)
    Call AddSheetCounters
End Sub

Public Sub AddSheetCounters()
    Dim i As Long, n As Long
    
    n = Me.Sheets.Count
    
    For i = 1 To n
        Me.Sheets(i).Range("X5").Value = "Sheet " & i
        Me.Sheets(i).Range("X6").Value = "of " & n
    Next i

End Sub

Edit the text for ranges X5 and X6 as you need. Every time a new sheet is added the macro is run. Unfortunately when a sheet is deleted, it won't and things will get out of sync.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM