This is close. It is however deleting the first 2 sheets (of which only the first contains MATCH), then leaves the last sheet (which is an empty sheet).
I added your code to mine and I run it like so: cscript //nologo //B xlsDeleteSheetIfContains.vbs C:\test.xls
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 MATCH 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
'oExcel.Appllication.DisplayAlerts=False 'this is intentionally wrong because it causes excel to exit immediately on failure
Dim oBook
Set oBook = oExcel.Workbooks.Open(sourceFile)
'search for MATCH and if found, delete the sheet it is in
'for my case, there would always be at least 1 sheet NOT containing MATCH
' - this avoids excel silently ignoring the sheet delete if there is only one sheet
' - to make this more useful for anyone, create an empty sheet before deleting sheet(s) with MATCH
' Add 1 empty sheet
'oBook.Worksheets.Add
On Error Resume Next
For Each oSheet In oBook.WorkSheets
Set oRange = oSheet.UsedRange
' Neither Work
' oRange.Find("searchString")
oSheet.Cells.Find("searchString")
If Err.Number=0 Then
oSheet.Delete
Err.Clear
End If
' Does Not Work
' If oExcel.WorksheetFunction.CountA(oSheet.Cells.Match("searchString")) = 0 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.
Dan
Bookmarks