Results 1 to 4 of 4

Thread: Looking for Excel VBA help

  1. #1
    Social Worker
    Join Date
    Nov 2006
    Location
    Australia
    Posts
    4,259

    Looking for Excel VBA help

    I'm writing some VBA code in Excel. There's a bit where I copy an existing "template" sheet in a workbook to a new sheet in the same workbook, and then rename it. (This is to do different months in a reporting setup, FYI).

    This works as long as a sheet with the new name doesn't already exist. If it does, Excel throws an error. Is there a way to check for the existence of a sheet with the given name, before doing the copy?

    Sample code is like this:

    Sub makeNewSheet()
    Dim target As Workbook
    Set target = ActiveWorkbook
    target.Worksheets(1).Copy before:=target.Worksheets(1)
    ' following line fails if "new sheet" already exists in active workbook
    target.Worksheets(1).Name = "new sheet"
    End Sub

  2. #2
    The bees are doing great New Romantic
    Join Date
    Jul 2003
    Location
    Wearing a beard made of bees.
    Posts
    6,294
    Code:
    Dim wsSheet As Worksheet
    On Error Resume Next
    Set wsSheet = Sheets("NewShtL")
    On Error GoTo 0
    If Not wsSheet Is Nothing Then
      MsgBox "I do exist"
    Else
      MsgBox "I do NOT exist"
    End If
    or

    Code:
    Dim sh As Worksheet, flg As Boolean
    For Each sh In Worksheets
    If sh.Name Like "NewSht*" Then flg = True: Exit For
    Next
    If flg = True Then
      MsgBox "Found!"
    Else
      Sheets.Add.Name = "NewSht"
    End If
    These aren't my snippets, I've just nicked them from elsewhere but they illustrate the two different ways that spring to mind to check wether something exists in VBA.

  3. #3
    Social Worker
    Join Date
    Nov 2006
    Location
    Australia
    Posts
    4,259
    Thank you!

    Have I mentioned how much I hate VBA?

  4. #4
    The bees are doing great New Romantic
    Join Date
    Jul 2003
    Location
    Wearing a beard made of bees.
    Posts
    6,294
    I don't mind it too much but since starting to get to grips with vb.net it is like stepping back into the dark ages at times.

Posting Permissions

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