简体   繁体   中英

How to check if worksheet exists?

I want to search a specific path's subfolders for an Excel book with a particular name. Once found, check if the document has a particular worksheet. If it doesn't, insert a sheet from another file and close the document.

I need to loop through every folder within a specific path (approx. 300 files in total).

Public strDestinationPath As String
Public strSearch As Variant    

Sub SearchFolders()

Range("B:M").ClearContents
Range("B1").Value = "Name"
Range("C1").Value = "Path"
Range("D1").Value = "Size (KB)"
Range("E1").Value = "DateLastModified"
Range("F1").Value = "Attributes"
Range("G1").Value = "DateCreated"
Range("H1").Value = "DateLastAccessed"
Range("I1").Value = "Drive"
Range("J1").Value = "ParentFolder"
Range("K1").Value = "ShortName"
Range("L1").Value = "ShortPath"
Range("M1").Value = "Type"
Range("B1").Select

Dim strPath As String
strPath = UserGetFolder & "\"

strSearch = InputBox("Enter Search Criteria (Case Sensitive)")

Dim OBJ As Object
Dim Folder As Object
Dim File As Object
Set OBJ = CreateObject("Scripting.FileSystemObject")
Set Folder = OBJ.GetFolder(strPath)

Call ListFiles(Folder)

Dim SubFolder As Object

For Each SubFolder In Folder.SubFolders
    Call ListFiles(SubFolder)
    Call GetSubFolders(SubFolder)
Next SubFolder

If Range("B2").Value = "" Then
    MsgBox "No Files Found", vbInformation
Else
End If

Range("B1").Select

End Sub


Private Sub ListFiles(ByRef Folder As Object)

For Each File In Folder.Files

    If InStr(File.Name, strSearch) <> 0 Then
    
        ActiveCell.Offset(1, 0).Select
        ActiveCell = File.Name
        ActiveCell.Offset(0, 1) = File.Path
        ActiveCell.Offset(0, 2) = (File.Size / 1024) 'IN KB
        ActiveCell.Offset(0, 3) = File.DateLastModified
        ActiveCell.Offset(0, 4) = File.Attributes
        ActiveCell.Offset(0, 5) = File.DateCreated
        ActiveCell.Offset(0, 6) = File.DateLastAccessed
        ActiveCell.Offset(0, 7) = File.Drive
        ActiveCell.Offset(0, 8) = File.ParentFolder
        ActiveCell.Offset(0, 9) = File.ShortName
        ActiveCell.Offset(0, 10) = File.ShortPath
        ActiveCell.Offset(0, 11) = File.Type
        
    Else
    End If
    
Next File

End Sub


Private Sub GetSubFolders(ByRef SubFolder As Object)

Dim FolderItem As Object

For Each FolderItem In SubFolder.SubFolders
    Call ListFiles(FolderItem)
    Call GetSubFolders(FolderItem)
    
    If File = Survey_Additional_Info Then
        Call WorksheetExists
        Call CopySheetToClosedWB
    Else
        'do nothing
    End If
    
Next FolderItem

End Sub


Function UserGetFolder() As String
    Dim fldr As FileDialog
    Dim sItem As String
    Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
    With fldr
        .Title = "Select a Folder"
        .AllowMultiSelect = False
        .InitialFileName = Application.DefaultFilePath
        If .Show <> -1 Then GoTo NextCode
        sItem = .SelectedItems(1)
    End With
NextCode:
    UserGetFolder = sItem
    Set fldr = Nothing
End Function


Function WorksheetExists(ByVal WorksheetName As String) As Boolean
    'Code to find sheet in a file - added by me not part of original

    Dim Sht As Worksheet

    For Each Sht In closedBook.Worksheets
        If Application.Proper(Time_Slots) = Application.Proper(Time_Slots) Then
            WorksheetExists = True
            Exit Function
        Else: Call CopySheetToClosedWB
            
        End If
    Next Sht
    WorksheetExists = False
End Function


Sub CopySheetToClosedWB() 'Copy Worksheet to a Closed Workbook
    Application.ScreenUpdating = False
 
    Set closedBook = Workbooks.Open("S:\Accordant\SUS\NewTimeSlotTab.xlsx")
    Sheets("Time_Slots").Copy Before:=closedBook.Sheets(Alternative_Locations)
    closedBook.Close SaveChanges:=True
 
    Application.ScreenUpdating = True
End Sub

My code works up to

Call WorksheetExists

The function WorksheetExists() has no idea what the variable closedBook is. That variable is not passed nor is it Publlic.

EDIT#1:

In general, you cannot use a variable until you have assigned a value to it.

For example before the line:

For Each Sht In closedBook.Worksheets

There should be a Dim statement for closedBook and a Set statement as well.

The Dim and Set should be placed within the function containing the For .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM