In VBA how to keep two worksheets and delete other sheets - excel

Hi everyone! I'm trying to write a method in VBA to keep 2 worksheets and delete others at the same time.
I already did the one that will keep one worksheet and delete others like this:
Sub delete_all_pages_except_main()
Dim ws As Worksheet
For Each ws In ThisWorkbook.Worksheets
Application.DisplayAlerts = False
If ws.Name <> "Home Page" Then
ws.Delete
End If
Next ws
End Sub
And I try to write it like this
If (ws.Name <> "Home Page" Or ws.Name <> "Data")
But VBA would accept it.
Can you guys help? Thank you.

This should do
Sub delete_all_pages_except_main()
Dim ws As Worksheet
Dim arr As Variant
Dim boo As Boolean
Application.DisplayAlerts = False
arr = Array("Home Page", "Data")
For Each ws In ThisWorkbook.Worksheets
boo = NoDel(ws.Name, arr)
If boo <> True Then ws.Delete
Next ws
Application.DisplayAlerts = True
End Sub
Function NoDel(ws As String, warr As Variant) As Boolean
NoDel = False
For i = LBound(warr, 1) To UBound(warr, 1)
If warr(i) = ws Then NoDel = True
Next i
End Function

Delete Sheets With Exceptions
Option Explicit
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Purpose: In a specified workbook, writes all the sheet names '
' not specified in an Exceptions array to a Result array, and '
' using the Result array deletes all the sheets in one go. '
' Remarks: This solution applies to worksheets and chartsheets. '
' Since there is no Sheet object, the For Next loop (instead '
' of the For Each Next loop) and the Object type have '
' to be used. '
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Sub deleteSheets(Book As Workbook, Exceptions As Variant)
' Program
Dim SheetsCount As Long: SheetsCount = Book.Sheets.Count
Dim Result As Variant: ReDim Result(SheetsCount)
Dim sh As Object, i As Long, j As Long
j = -1
For i = 1 To SheetsCount: GoSub checkName: Next i
If j = -1 Then GoTo NothingToDelete
If j = SheetsCount - 1 Then GoTo NoExceptions
GoSub deleteSheetsInOneGo
MsgBox "Deleted '" & j + 1 & "' sheets.", vbInformation, "Success"
Exit Sub
' Subroutines
checkName:
Set sh = Book.Sheets(i)
If IsError(Application.Match(sh.Name, Exceptions, 0)) Then
j = j + 1
Result(j) = sh.Name
End If
Return
deleteSheetsInOneGo:
ReDim Preserve Result(j)
Application.DisplayAlerts = False
Book.Sheets(Result).Delete
Application.DisplayAlerts = True
Return
' Labels
NothingToDelete:
MsgBox "Sheets already deleted.", vbCritical, "Nothing to Delete"
Exit Sub
NoExceptions:
MsgBox "Cannot delete all sheets.", vbCritical, "No Exceptions"
Exit Sub
End Sub
' Usage Example
Sub runDeleteSheets()
Dim SheetNames As Variant: SheetNames = Array("Home Page", "Data")
deleteSheets ThisWorkbook, SheetNames
End Sub

Related

Excel Macro/Visual Basics Code: select all sheets except 2

I need the VBA code to select ALL sheets (number and sheet names will vary from time to time) in a workbook except two specific sheets named "Overview" and "Index" (which also happens to be the left-most sheets on the tab list)
Is there "generic" code that can do this without naming each sheet (other than the two sheets that I do NOT want selected)
I tried the below code first to see if I could select all sheets except one:
Sub Macro1()
Dim i As Long
Sheet1.Select
For i = 2 To ThisWorkbook.Sheets.Count
If Sheets(i).Name <> "Overview" Then Sheets(i).Select Replace:=False
Next i
End Sub
but I kept getting a run-time error '1004; message and when I clicked debug it would highlight the "sheet1.slecet" line of code.
Here's an option.
Sub SelectWS()
Dim WS As Worksheet
Dim I As Long
Dim N As Long
Dim Fnd As Boolean
Dim Vis As Boolean
N = 0
For Each WS In ThisWorkbook.Worksheets
Vis = (WS.Visible = xlSheetVisible)
If Vis = False Then N = N + 1
If WS.Name <> "Overview" And WS.Name <> "Index" And Vis Then
Fnd = True
If ActiveSheet.Name = "Overview" Or ActiveSheet.Name = "Index" Then
WS.Activate
WS.Select
Else
WS.Select (False)
End If
End If
Next WS
If Not Fnd Then
MsgBox "No suitable WS found.", vbInformation + vbOKOnly, "Error:"
ElseIf N > 0 Then
MsgBox "Found " & N & " hidden Worksheet(s) - not selectable.", vbInformation + vbOKOnly, "Notice:"
End If
End Sub
Try this:
Sub Macro1()
Dim iSel As Long, ws As Worksheet
For Each ws In ThisWorkbook.Worksheets
If IsError(Application.Match(ws.Name, _
Array("Overview", "Index"), 0)) Then
ws.Select Replace:=(iSel = 0) 'only Replace for first-selected sheet
iSel = iSel + 1 'increment selected sheet count
End If
Next ws
End Sub
(assumes no hidden sheets)

Save Selected Sheets in another workbook

Wondering why I can't do :
For i = 1 To ThisWorkbook.Sheets.Count
If ThisWorkbook.Sheets(i).Name <> "DO NOT SAVE" Then ThisWorkbook.Sheets(i).Select Replace:=False
Next i
Selection.Copy
what would be the best way to save all sheets which does not match DO NOT SAVE name in another wb ?
Try this:
Sub Tester()
Dim ws As Worksheet, arr(), i As Long
ReDim arr(0 To ThisWorkbook.Worksheets.Count - 2)
For Each ws In ThisWorkbook.Worksheets
If ws.Name <> "DO NOT SAVE" Then
arr(i) = ws.Name
i = i + 1
End If
Next ws
Worksheets(arr).Copy
End Sub
A Reflection on the Sheets' Visibility
To export a single sheet to a new workbook, the sheet has to be visible.
To export multiple sheets (using an array of sheet names) to a new workbook, at least one of the sheets has to be visible, while very hidden sheets will not get exported (no error though).
In a given workbook, the following procedure will copy all its sheets, except the ones whose names are in a given array (Exceptions), to a new workbook if at least one of the sheets is visible.
Before copying, it will 'convert' the very hidden sheets to hidden and after the copying, it will 'convert' the originals and copies to very hidden.
Option Explicit
Sub ExportSheets( _
ByVal wb As Workbook, _
ByVal Exceptions As Variant)
Dim shCount As Long: shCount = wb.Sheets.Count
Dim SheetNames() As String: ReDim SheetNames(1 To shCount)
Dim sh As Object
Dim coll As Object
Dim Item As Variant
Dim n As Long
Dim VisibleFound As Boolean
Dim VeryHiddenFound As Boolean
For Each sh In wb.Sheets
If IsError(Application.Match(sh.Name, Exceptions, 0)) Then
Select Case sh.Visible
Case xlSheetVisible
If Not VisibleFound Then VisibleFound = True
Case xlSheetHidden ' do nothing
Case xlSheetVeryHidden
If Not VeryHiddenFound Then
Set coll = New Collection
VeryHiddenFound = True
End If
coll.Add sh.Name
End Select
n = n + 1
SheetNames(n) = sh.Name
End If
Next sh
If n = 0 Then
MsgBox "No sheet found.", vbExclamation
Exit Sub
End If
If Not VisibleFound Then
MsgBox "No visible sheet found.", vbExclamation
Exit Sub
End If
If n < shCount Then ReDim Preserve SheetNames(1 To n) ' n - actual count
If VeryHiddenFound Then ' convert to hidden
For Each Item In coll
wb.Sheets(Item).Visible = xlSheetHidden
Next Item
End If
wb.Sheets(SheetNames).Copy ' copy to new workbook
If VeryHiddenFound Then ' revert to very hidden
Dim dwb As Workbook: Set dwb = Workbooks(Workbooks.Count)
For Each Item In coll
wb.Sheets(Item).Visible = xlSheetVeryHidden
dwb.Sheets(Item).Visible = xlSheetVeryHidden
Next Item
End If
MsgBox "Sheets exported: " & n, vbInformation
End Sub
Sub ExportSheetsTEST()
Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
ExportSheets wb, Array("DO NOT SAVE")
End Sub
Alternatively you could use the following snippet:
Sub CopyWorkbook()
Dim i As Integer
For i = 1 To ThisWorkbook.Sheets.Count
If ThisWorkbook.Sheets(i).Name <> "DO NOT SAVE" Then
Dim rng As Range
Windows("SOURCE WORKBOOK").Activate
rng = ThisWorkbook.Sheets(i).Cells
rng.Copy Before:=Workbooks("TARGET WORKBOOK").Sheets(i)
End If
Next i
End Sub

How do I create a vbYesNo MsgBox outside of For Each loop?

What I'm trying to do:
If sheets exist that are NOT named "Macro" > prompt user with MsgBox > if yes, delete all sheets not named "Macro"
But only show MsgBox ONCE (do not show MsgBox for each sheet if more than 1 sheet exists)
Problem with current code:
Still getting MsgBox prompt when "Macro" is the only sheet that exists.
Current code:
Sub reset()
Dim conditionMet As Boolean
Dim answer As Integer
conditionMet = FALSE
answer = MsgBox("There Is already data here. Click Yes To delete reset macro.", vbQuestion + vbYesNo)
Application.DisplayAlerts = FALSE
For Each Sheet In ThisWorkbook.Worksheets
If Sheet.Name <> "Macro" Then
conditionMet = TRUE
Else
Exit Sub
End If
Next Sheet
If conditionMet Then
If answer = vbYes Then
Sheet.Delete
Else
Exit Sub
End If
Else
Exit Sub
End If
Application.DisplayAlerts = TRUE
End Sub
Here's one approach:
Const KEEP_THIS As String = "Macro"
Dim ws As Worksheet
On Error Resume Next
Set ws = ThisWorkbook.Sheets(KEEP_THIS)
On Error GoTo 0
If ws Is Nothing Or ThisWorkbook.Worksheets.Count = 1 Then Exit Sub 'no "Macro" sheet
If MsgBox("Delete all data sheets?", vbQuestion + vbYesNo) <> vbYes Then Exit Sub
'remove all non-Macro sheets
For i = ThisWorkbook.Worksheets.Count To 1 Step -1
With ThisWorkbook.Worksheets(i)
If .Name <> KEEP_THIS Then .Delete
End With
Next i
Delete All Sheets Except a Specified One
The following shows how to avoid a few (less) common surprises.
The Code
Option Explicit
Sub resetWorkbook()
Const SheetName As String = "Macro"
Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
' There has to be at least one sheet in the workbook.
If wb.Sheets.Count = 1 Then Exit Sub
' Check for existence.
On Error Resume Next
Dim sh As Object: Set sh = wb.Sheets(SheetName)
On Error GoTo 0
If sh Is Nothing Then Exit Sub
If MsgBox("There Is already data here. Click Yes To delete reset macro.", _
vbQuestion + vbYesNo) = vbNo Then Exit Sub
' An only sheet in a workbook has to be visible.
If Not sh.Visible = xlSheetVisible Then
sh.Visible = xlSheetVisible
End If
' Write the other sheet names to an array.
Dim SheetNames() As String: ReDim SheetNames(1 To wb.Sheets.Count - 1)
Dim n As Long
For Each sh In wb.Sheets
' Allow case-insensitivity i.e. A = a.
If StrComp(sh.Name, SheetName, vbTextCompare) <> 0 Then
n = n + 1
SheetNames(n) = sh.Name
End If
Next sh
' Delete sheets in one go with no pop-ups.
Application.DisplayAlerts = False
wb.Sheets(SheetNames).Delete
Application.DisplayAlerts = True
' Inform.
MsgBox "Number of sheets deleted: " & n, vbInformation, "Success"
End Sub

IFERROR in in this macro?

The problem is that when I change the value in I16 or I17 I get an error. How
can I prevent this error from happening?
I check in I16 and I17 for the sheetnames, because every week an updated sheet comes available.
Thank you
Sub Compare()
Call compareSheets(range("I16").Value, range("I17").Value)
End Sub
Sub compareSheets(Sofon As String, Sofon2 As String)
Dim mycell As range
Dim mydiffs As Integer
For Each mycell In ActiveWorkbook.Worksheets(Sofon2).range("M:M")
If Not mycell.Value = ActiveWorkbook.Worksheets(Sofon).Cells(mycell.Row, mycell.Column).Value Then
mycell.Interior.Color = vbYellow
mydiffs = mydiffs + 1
End If
Next
MsgBox mydiffs & " differences found in Column M (Salesman)", vbInformation
ActiveWorkbook.Sheets(Sofon2).Select
End Sub
Just to show what I was thinking.
I agree with puzzlepiece87 that On Error is finicky, but with something this simple I would use it to avoid the excess loops.
Sub compareSheets(Sofon As String, Sofon2 As String)
Dim mycell As Range
Dim mydiffs As Integer
On Error GoTo nosheet
For Each mycell In ActiveWorkbook.Worksheets(Sofon2).Range("M:M")
If Not mycell.Value = ActiveWorkbook.Worksheets(Sofon).Cells(mycell.Row, mycell.Column).Value Then
mycell.Interior.Color = vbYellow
mydiffs = mydiffs + 1
End If
Next
MsgBox mydiffs & " differences found in Column M (Salesman)", vbInformation
ActiveWorkbook.Sheets(Sofon2).Select
Exit Sub
nosheet:
If Err.Number = 9 Then
MsgBox "One or both sheets do not exist"
Else
MsgBox Err.Description
End If
End Sub
Since the OP wanted an ISERROR type of solution, I decided to post the code which incorporates a function to check if a sheet exists in a workbook. The concept is similar to answers already posted, but it keeps any On Error statements strictly inside the function and uses regular code blocks to evaluate errors.
Sub Compare()
Dim bGo As Boolean
Dim s1 As String, s2 As String
s1 = Range("I16").Value2
s2 = Range("I17").Value2
If Not WorksheetExist(s1) Then
bGo = False
MsgBox "The sheet " & s1 & " does not exist in this workbook."
End If
If Not WorksheetExist(s2) Then
bGo = False
MsgBox "The sheet " & s2 & " does not exist in this workbook."
End If
If bGo Then compareSheets s1, s2
End Sub
Function WorksheetExist(sName As String, Optional wb As Workbook) As Boolean
Dim wbCheck As Workbook, ws As Worksheet
If wb Is Nothing Then Set wbCheck = ThisWorkbook Else: Set wbCheck = wb
On Error Resume Next
Set ws = wbCheck.Sheets(sName)
On Error GoTo 0
If Not ws Is Nothing Then WorksheetExist = True Else: WorksheetExist = False
End Function
And, based on #puzzlepiece87 methodology, here is an improved WorksheetExist Function that eliminates of On Error statements altogether.
Function WorksheetExist(sName As String, Optional wb As Workbook) As Boolean
Dim wbCheck As Workbook, ws As Worksheet
If wb Is Nothing Then Set wbCheck = ThisWorkbook Else: Set wbCheck = wb
WorksheetExist = False
For Each ws In wbCheck.Worksheets
If ws.Name = sName Then
WorksheetExist = True
Exit For
End If
Next
End Function
You could use something similar to this to call compareSheets. It will warn you if either of the two ranges do not correspond to sheet names and won't call compareSheets if true.
Dim Sheet1 As Worksheet
Dim boolI16SheetCheck As Boolean
Dim boolI17SheetCheck As Boolean
boolI16SheetCheck = False
boolI17SheetCheck = False
For Each Sheet1 in ActiveWorkbook.Worksheets
If Sheet1.Name = Activesheet.Range("I16").Value Then boolI16SheetCheck = True
If Sheet1.Name = Activesheet.Range("I17").Value Then boolI17SheetCheck = True
If boolI16SheetCheck = True And boolI17SheetCheck = True Then
Call compareSheets(range("I16").Value, range("I17").Value)
Exit Sub
End If
Next Sheet1
If boolI16SheetCheck = False Then
If boolI17SheetCheck = False Then
Msgbox "Neither I16 nor I17 sheet found."
Else
Msgbox "I16 sheet not found."
End If
Else
Msgbox "I17 sheet not found."
End If
End Sub

loop to delete table rows through numerous worksheets based on a cell value

working on a loop to delete stock info from numerous worksheets in a workbook. Each sheet is named, "Client_ClientFirstName", and each table in each worksheet is the same as the worksheet name. here is the code ive come up with so far, any and all advice is appreciated.
Sub RemoveTickerFromAccounts()
Dim Client As Worksheet
Dim varTickerToFind As String
varTickerToFind = Worksheets("Entry").Cells(5, 1)
Dim tblSearchTable As Range
For Each Client In ActiveWorkbook.Worksheets
If InStr(1, Client.Name, "Client_", vbTextCompare) Then
'ws.Range("B30").Select
Worksheets(Client.Name).Activate
'tblSearchTable = ActiveSheet.ListObjects(1)
ActiveSheet.Range("b30").Select
If Selection.ListObject.Name = Client.Name Then
'tblSearchTable = "Table14"
'tblSearchTable = ActiveSheet.ListObjects(Client.Name).Select
For i = 1 To ActiveSheet.ListObjects(Client.Name).ListRows.Count
If ActiveSheet.ListObject.ListRows(i, 1).Value = varTickerToFind _
Then
tblSearchTable.ListRows(i).Delete
Exit For
Else
MsgBox "Unable to Find Ticker"
Exit For
End If
Next i
End If
End If
Next Client
End Sub
Tested:
Sub RemoveTickerFromAccounts()
Dim Client As Worksheet
Dim varTickerToFind As String
Dim tblSearch As ListObject
Dim bFound As Boolean, i As Long
varTickerToFind = Worksheets("Entry").Cells(5, 1).Value
For Each Client In ActiveWorkbook.Worksheets
If Client.Name Like "Client_*" Then
Set tblSearch = Client.ListObjects(1)
For i = 1 To tblSearch.ListRows.Count
If tblSearch.ListRows(i).Range.Cells(1).Value = varTickerToFind Then
tblSearch.ListRows(i).Delete
bFound = True
Exit For
End If
Next i
If Not bFound Then
MsgBox "Unable to Find Ticker '" & varTickerToFind & "'"
End If
End If
Next Client
End Sub

Resources