Consulting

Results 1 to 14 of 14

Thread: Solved: reset Excel sheet count?

  1. #1
    VBAX Mentor tpoynton's Avatar
    Joined
    Feb 2005
    Location
    Clinton, MA
    Posts
    399
    Location

    Solved: reset Excel sheet count?

    Greetings - i have the following bit of code to delete all but the visible sheet. it works fine, but I was wondering if there is a way to set the sheetcount back to 1 as part of this.

    Right now, if I have sheets named like "sheet1", "sheet2" etc all the way up to "sheet30" and I run this procedure, it starts again at number 31 after sheets 1-30 are deleted. is there a way to reset this back to the lowest possible number? restarting excel does this, but I am wondering if it can be done through VBA.

    [vba]Public Sub DeleteSheets()
    Dim currentSheet As String
    Dim varAnswer As String
    Dim wsSheet As Worksheet
    Dim strName As String
    currentSheet = ActiveSheet.Name

    varAnswer = MsgBox("This will delete all sheets except for the sheet named '" _
    + currentSheet + "'" + (Chr(13)) + (Chr(13)) + _
    "Click Yes to irreversibly erase the other sheets, or No to cancel this procedure", _
    vbYesNo, "Warning - This Procedure Can Not Be Undone!")

    If varAnswer = vbNo Then
    Exit Sub
    Else:
    Application.DisplayAlerts = False

    With ActiveSheet
    For Each wsSheet In Worksheets
    strName = wsSheet.Name

    If strName <> currentSheet Then
    wsSheet.Delete
    End If
    Next wsSheet
    End With
    end if
    Application.DisplayAlerts = True
    End Sub[/vba]

    What happens is that i have other procedures which add new sheets through VBA using worksheets.add. It is not that big of a deal, but I am curious!

  2. #2
    Moderator VBAX Master austenr's Avatar
    Joined
    Sep 2004
    Location
    Maine
    Posts
    2,033
    Location
    Is this what you want?


    [VBA] Public Sub DeleteSheets()
    Dim currentSheet As String
    Dim varAnswer As String
    Dim wsSheet As Worksheet
    Dim strName As String
    currentSheet = ActiveSheet.Name

    varAnswer = MsgBox("This will delete all sheets except for the sheet named '" + _
    currentSheet + "'" + (Chr(13)) + (Chr(13)) + "Click Yes to irreversibly erase " & _
    "the other sheets, or No to cancel this procedure", vbYesNo, _
    "Warning - This Procedure Can Not Be Undone!")

    If varAnswer = vbNo Then
    Exit Sub
    Else:
    Application.DisplayAlerts = False

    With ActiveSheet
    For Each wsSheet In Worksheets
    strName = wsSheet.Name

    If strName <> currentSheet Then
    wsSheet.Delete
    End If
    Next wsSheet
    End With
    End If
    ActiveSheet.Name = "Sheet1"
    Application.DisplayAlerts = True
    End Sub
    [/VBA]
    Last edited by geekgirlau; 12-21-2005 at 04:00 PM. Reason: Put line breaks in code
    Peace of mind is found in some of the strangest places.

  3. #3
    VBAX Mentor tpoynton's Avatar
    Joined
    Feb 2005
    Location
    Clinton, MA
    Posts
    399
    Location
    Thanks for the reply austenr, and my apologies for not being clear!

    If I am not mistaken, that will set the undeleted sheet to be named "Sheet1". I dont want to change the name of the remaining sheet, but do want all future sheets that are added to start at the lowest possible number. right now, it picks up where it left off. if Excel is restarted, it goes back to using the lowest possible number - i would like to, if possible, reset that counter without restarting excel!

    I am constantly amazed at how many settings there are, and I am pretty sure it is available somewhere!

  4. #4
    Administrator
    VP-Knowledge Base
    VBAX Grand Master mdmackillop's Avatar
    Joined
    May 2004
    Location
    Scotland
    Posts
    14,489
    Location
    Hi both,
    Can you please use line breaks in the code, or I'll need to get a second screen!
    MVP (Excel 2008-2010)

    Post a workbook with sample data and layout if you want a quicker solution.


    To help indent your macros try Smart Indent

    Please remember to mark threads 'Solved'

  5. #5
    VBAX Mentor tpoynton's Avatar
    Joined
    Feb 2005
    Location
    Clinton, MA
    Posts
    399
    Location
    I was going to add line breaks, but someone has beat me to it!

    I'll also work on creating a file to upload...

  6. #6
    Administrator
    VP-Knowledge Base VBAX Grand Master mdmackillop's Avatar
    Joined
    May 2004
    Location
    Scotland
    Posts
    14,489
    Location
    Yeah.
    I did that.
    I see your problem, but I don't know if there is a "real" solution, but here's a possible workaround. It works with one error, but not two. Add the code to ThisWorkbook module.
    [VBA]Private Sub Workbook_NewSheet(ByVal Sh As Object)
    On Error GoTo errh
    Sh.Name = "Sheet" & Sheets.Count
    Exit Sub
    errh:
    Sh.Name = "Sheet" & Sheets.Count + 1
    End Sub[/VBA]
    MVP (Excel 2008-2010)

    Post a workbook with sample data and layout if you want a quicker solution.


    To help indent your macros try Smart Indent

    Please remember to mark threads 'Solved'

  7. #7
    VBAX Mentor tpoynton's Avatar
    Joined
    Feb 2005
    Location
    Clinton, MA
    Posts
    399
    Location

    Here's a sheet to play with

    I just saw your post, and will play with that soon. here is a demo file to tinker with...i need to take a break, but will check in again tomorrow...

    THANKS!

    PS - noticed the sheets.count property is read only...that may be a problem!

  8. #8
    Moderator VBAX Master geekgirlau's Avatar
    Joined
    Aug 2004
    Location
    Melbourne, Australia
    Posts
    1,464
    Location
    Personally I never leave a sheet named "Sheet1" anyway - I prefer to use a name that tells me what's on the sheet!

  9. #9
    VBAX Mentor tpoynton's Avatar
    Joined
    Feb 2005
    Location
    Clinton, MA
    Posts
    399
    Location

    Not ideal, but...

    attached is a solution i can live with; i was hoping to not have to go through all of my code again, but i can use search and replace to use the addsheets function instead of worksheets.add.

    i'll mark as solved, but if anyone comes up with a more elegant solution, i'm all ears...

  10. #10
    Administrator
    Chat VP VBAX Guru johnske's Avatar
    Joined
    Jul 2004
    Location
    Townsville, Australia
    Posts
    2,872
    Location
    [vba]Option Explicit

    Sub DeleteSheets()
    Dim Answer As String, Sheet As Worksheet
    Answer = MsgBox("This will delete all sheets except for the sheet named '" & _
    ActiveSheet.Name & "'" & vbNewLine & vbNewLine & _
    "Click Yes to irreversibly erase the other sheets, or No to cancel " & _
    "this procedure", vbYesNo, "Warning - This Procedure Can Not Be Undone!")
    If Answer = vbNo Then
    Exit Sub
    Else
    Application.DisplayAlerts = False
    For Each Sheet In Worksheets
    If Sheet.Name <> ActiveSheet.Name Then Sheet.Delete
    Next
    Application.DisplayAlerts = True
    End If
    End Sub

    Sub AddSheets()
    Dim N As Long
    Worksheets.Add after:=Sheets(Sheets.Count)
    ActiveSheet.Name = "EZA" & Sheets.Count - 1
    For N = 1 To Sheets.Count
    ThisWorkbook.VBProject.VBComponents(Sheets(N).CodeName).Name = "Sheet" & N
    Next
    End Sub[/vba]FYI, although it's possible to use the "+" symbol for concatenation, it is neither good nor accepted practice. It's best to reserve this symbol for additions only and to use the "&" symbol for concatenation. Here is what's said in the VBA Help files regarding this

    Quote Originally Posted by VBA Help files
    Remarks

    When you use the + operator, you may not be able to determine whether addition or string concatenation will occur. Use the & operator for concatenation to eliminate ambiguity and provide self-documenting code.
    Also, for new lines it's better practice to use vbNewLine (or even vbCr, or vbLf, or vbCrLf) rather than Chr(13)
    You know you're really in trouble when the light at the end of the tunnel turns out to be the headlight of a train hurtling towards you

    The major part of getting the right answer lies in asking the right question...


    Made your code more readable, use VBA tags (this automatically inserts [vba] at the start of your code, and [/vba ] at the end of your code) | Help those helping you by marking your thread solved when it is.

  11. #11
    Distinguished Lord of VBAX VBAX Grand Master Bob Phillips's Avatar
    Joined
    Apr 2005
    Posts
    25,453
    Location
    Quote Originally Posted by johnske
    Also, for new lines it's better practice to use vbNewLine (or even vbCr, or vbLf, or vbCrLf) rather than Chr(13)
    vbNewLine is best. Macs recognise vbNewLine.
    Last edited by Bob Phillips; 12-22-2005 at 11:50 AM.

  12. #12
    VBAX Mentor tpoynton's Avatar
    Joined
    Feb 2005
    Location
    Clinton, MA
    Posts
    399
    Location
    THANKS - that works quite nicely! regarding my bad coding habits, I have a bunch...thanks for pointing them out as it helps me develop new and better ones!

    Regarding chr(13), I looked all over to find out how to add a blank line in messageboxes and found that. It also works on Macs, but is certainly not intuitive! thanks again!

  13. #13
    Administrator
    Chat VP VBAX Guru johnske's Avatar
    Joined
    Jul 2004
    Location
    Townsville, Australia
    Posts
    2,872
    Location
    Quote Originally Posted by tpoynton
    THANKS - that works quite nicely! regarding my bad coding habits, I have a bunch...thanks for pointing them out as it helps me develop new and better ones!

    Regarding chr(13), I looked all over to find out how to add a blank line in messageboxes and found that. It also works on Macs, but is certainly not intuitive! thanks again!
    Not a prob, we're all here to learn. Happy holidays!
    You know you're really in trouble when the light at the end of the tunnel turns out to be the headlight of a train hurtling towards you

    The major part of getting the right answer lies in asking the right question...


    Made your code more readable, use VBA tags (this automatically inserts [vba] at the start of your code, and [/vba ] at the end of your code) | Help those helping you by marking your thread solved when it is.

  14. #14
    VBAX Newbie
    Joined
    Apr 2015
    Posts
    2
    Location

    Post

    This code re-numbers all worksheets to back-fill the empty sheet indexes when a workbook is saved.
    Excel will start indexing at the next available (new) sheet index when workbook is re-opened.


    I too wanted a way to re-index the worksheets so I can dynamically add/delete many worksheets within VBA. The benefit to dynamically adding and deleting sheets vs having predefined worksheets hidden is file size and time to load the workbook.

    My workbook sheets contain a lot of data... each worksheet has repeated formats and code embedded. I found it best to keep one 'template' worksheet hidden, then copy it and rename the copied sheet within VBA code. The copy/rename method duplicates the code and sheet format from the template sheet while keeping the sheet count (and data file size) to a minimum.

    Problem is... deleting the newly made sheets when I'm done with them makes holes in Excel's sheet indexing. The last sheet index grows and grows every time the workbook is re-open.

    I wrote this solution to be executed when a workbook is saved. Tested to work OK in Excel 2003.
    - It should be placed in the VBA editor's 'ThisWorkbook' object.
    - This is meant to be more of a maintenance tool... and there is no error trapping in this code (feel free to add it!). All worksheets are temporally re-indexed above the highest existing sheet index, so make sure there is enough index room to do that.

    The way it works:
    1) Function calls when workbook was chosen to save.
    2) Find the highest number sheet in your workbook.
    3) Make room to renumber all sheets low, to do this... Renumber all sheets to be greater than the highest existing sheet number.
    4) Now that all low sheet numbers are free - renumber them again them to start at index=1.

    Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
    
    '===============================================================================================
    '- Renumber all sheets to back-fill empty sheet indexes before saving workbook.
    '- Allows Excel to begin indexing sheets to next lowest available sheet index when re-opened.
    '- Needs Tools/Reference "Microsoft Visual Basic for Applications Extensibility"
    '===============================================================================================
    
    Dim ws As Worksheet
    Dim i As Integer
    
    Dim sThisSheetCodeName As String
    Dim iThisSheetNumber As Integer
    Dim iMaxSheetNumber As Integer
    
    Application.ScreenUpdating = False
        
        '1st - Find the highest sheet number
        For Each ws In ActiveWorkbook.Worksheets
            sThisSheetCodeName = ws.Parent.VBProject.VBComponents(ws.CodeName).Properties("_CodeName").Value
            iThisSheetNumber = Right(sThisSheetCodeName, Len(sThisSheetCodeName) - 5)
            If iThisSheetNumber > iMaxSheetNumber Then iMaxSheetNumber = iThisSheetNumber
        Next
        
        '2nd - Renumber all sheets to be > than highest sheet number
        i = iMaxSheetNumber + 1
        For Each ws In ActiveWorkbook.Worksheets
            i = i + 1
            ws.Parent.VBProject.VBComponents(ws.CodeName).Properties("_CodeName").Value = "Sheet" & i
        Next
            
        '3rd - Now that all sheets are > max sheet number. Renumber all sheets to start with 1
        i = 0
        For Each ws In ActiveWorkbook.Worksheets
            i = i + 1
            ws.Parent.VBProject.VBComponents(ws.CodeName).Properties("_CodeName").Value = "Sheet" & i
        Next
    
    Application.ScreenUpdating = True
    
    End Sub

    I'm new to this message board and wanted to give back.

    Credit goes to BrianB for his message on this post exposing me to the code line:
    ' ws.Parent.VBProject.VBComponents(ws.CodeName).Properties("_CodeName").Value '


    Thanks Brian, this code line was key in finding a solution for my sheet indexing problem!
    Last edited by vmaxer; 04-06-2015 at 05:40 PM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •