Avatar of Wm Allen Smith
Wm Allen Smith

asked on 

VBA to Insert Named Sheet if not Already Exists

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

VBA

Avatar of undefined
Last Comment
Wm Allen Smith

8/22/2022 - Mon