troubleshooting Question

VBA to Insert Named Sheet if not Already Exists

Avatar of Wm Allen Smith
Wm Allen Smith asked on
VBA
12 Comments1 Solution24 ViewsLast Modified:
I have code that will  loop through a folder and insert a named worksheet called "DATA" into each workbook of the folder. I want to execute the code only when the name sheet does not exist. In this way, I would not have to move the files with the missing sheet to a different folder to run the code.

The Code:

Sub Insertworksheet()
    Dim path As String
    Dim file As String
    Dim wkbk As Workbook
    Dim rCell As Range

    Application.ScreenUpdating = False
    Application.DisplayAlerts = False


    path = "C:\pathname\*"
    file = Dir(path)

    Do While Not file = ""
      Application.DisplayAlerts = False
        Workbooks.Open (path & file)
        Set wkbk = ActiveWorkbook
        Sheets.Add After:=Sheets(Sheets.Count)
        On Error GoTo Sheet_Exists
        ActiveSheet.Name = "DB Output"
        On Error GoTo 0
        ThisWorkbook.Sheets("DBOutput").Range("A1:B335").Copy Destination:=wkbk.Sheets("DB Output").Range("A1")

        For Each rCell In wkbk.Sheets("DB Output").UsedRange
            If InStr(rCell.Formula, ThisWorkbook.Name) > 0 Then
               ' rCell.Replace What:="[*]", Replacement:=""
                rCell.Replace What:="'*!'", Replacement:="WORKSHEET!"
            End If
            
       ' Sheets("DBOutput").Visible = False
        Next

        wkbk.Save
        wkbk.Close
        file = Dir
    Loop

    Application.ScreenUpdating = True
    Application.DisplayAlerts = True
    Exit Sub

Sheet_Exists:
   Sheets("DB Output").Delete
   ' Sheets("DB Output").Save
    Resume
End Sub

Open in new window

ASKER CERTIFIED SOLUTION
gowflow
Partner

Our community of experts have been thoroughly vetted for their expertise and industry experience.

Join our community to see this answer!
Unlock 1 Answer and 12 Comments.
Start Free Trial
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 12 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros