troubleshooting Question

VBA to Insert Named Sheet if not Already Exists

Avatar of Wm Allen Smith
Wm Allen Smith asked on
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

        file = Dir

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

   Sheets("DB Output").Delete
   ' Sheets("DB Output").Save
End Sub
Join the community to see this answer!
Join our exclusive community to see this answer & millions of others.
Unlock 1 Answer and 12 Comments.
Join the Community
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