Results 1 to 6 of 6

Thread: Delete Sheet If Contains

Hybrid View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Junior Member
    Join Date
    Apr 2012
    Posts
    5
    Rep Power
    0
    We're clearly using different tools to accomplish similar things. Thanks for your help! It helped point me in the right direction.

    Here's what worked for me: cscript //nologo //B xlsDeleteSheetIfContains.vbs searchString C:\test.xlsx

    Code:
    If WScript.Arguments.Count < 2 Then
    	WScript.Echo "Error! Please specify the MATCH to delete Sheet and the file to edit. Usage: wscript xlsDeleteSheetIfContains.vbs searchString SourcePath.xls"
    	Wscript.Quit
    End If
    Set ArgObj = WScript.Arguments
    Dim ArgObj, searchString, sourceFile
    searchString = ArgObj(0)
    sourceFile = ArgObj(1)
    
    Dim oExcel
    Set oExcel = CreateObject("Excel.Application")
    oExcel.DisplayAlerts=False
    
    Dim oBook
    Set oBook = oExcel.Workbooks.Open(sourceFile)
    
    'search for searchString and if found, delete the sheet it is in
    ' Add 1 empty sheet - just in case all sheets contain searchString - we must leave 1 sheet before we exit
    oBook.Worksheets.Add
    
    On Error Resume Next
    For Each oSheet In oBook.WorkSheets
    	Set oRange = oSheet.UsedRange
    	Set oTarget = oRange.Find(searchString)
    	If Not oTarget Is Nothing Then
    		oSheet.Delete
    	End If
    	' delete all empty sheets
    	If oExcel.WorksheetFunction.CountA(oSheet.Cells) = 0 Then
    		oSheet.Delete
    	End If
    Next
    
    oBook.Save
    oBook.Close True
    oExcel.Quit
    WScript.Quit
    set oSheet = Nothing
    set oBook = Nothing
    set oExcel = Nothing
    Thanks again!
    Dan

  2. #2
    Senior Member
    Join Date
    Jun 2012
    Posts
    337
    Rep Power
    14
    I work in VBA.

    Please keep it simple.

    Code:
    If WScript.Arguments.Count < 2 Then
    WScript.Echo "Error! Please specify the MATCH to delete Sheet and the file to edit. Usage: wscript xlsDeleteSheetIfContains.vbs searchString SourcePath.xls"
    Wscript.Quit
    End If
    
      on error resume next
    
      set wb=getobject(WScript.Arguments(1))
      wb.application.displayalerts=false
    
        for each sh in wb.sheets
          sh.cells.find(WScript.Arguments(0),,,1).clearcontents
          if err.number=0 then sh.delete
          err.clear
        next
        wb.close true
    
      set wb=nothing

Similar Threads

  1. Replies: 1
    Last Post: 05-19-2013, 02:37 PM
  2. Replies: 1
    Last Post: 02-10-2013, 06:21 PM
  3. Replies: 2
    Last Post: 12-26-2012, 08:31 AM
  4. Replies: 2
    Last Post: 11-17-2011, 07:49 PM
  5. Replies: 1
    Last Post: 10-28-2011, 09:27 AM

Posting Permissions

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