Removing Worksheets via Worksheets.Remove() - vba

I am attempting to remove Worksheets via VBA code. The general idea here is that when the number of worksheets reaches 18, we delete the end worksheet. Now as worksheets are a collection, I have attempted:
If Worksheets.Count = 18 Then
Worksheets.Remove (Worksheets.Count)
End If
But get an error. Any ideas?
Thanks!

You need to disable alerts first, and then use the delete method.
Application.DisplayAlerts = False
Worksheets(Worksheets.Count).Delete
Application.DisplayAlerts = True

Try using Worksheets.Delete("SheetName") instead: https://msdn.microsoft.com/en-us/library/office/ff837404.aspx.
If Worksheets.Count = 18 Then
Worksheets.Delete(Worksheets.Count)
End If

Try this:
Sub WorksheetDelete()
Application.DisplayAlerts = False 'To avoid display alert
Do Until ActiveWorkbook.Worksheets.Count>=18
ActiveWorkbook.Worksheets(18).Delete 'Delete the 18th worksheet
Loop
Application.DisplayAlerts = True 'Turn on the Alerts
End Sub

Related

buttons not copying with sheet excel vba

I have some macros that copy my sheet in excel,and delete certain data. Unfortunately the buttons to which the macros are assigned do not copy over when the macros are run.
Sub CandD()
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Dim sh As Shape, strtSh As Worksheet
Set strtSh = ActiveSheet
Sheets("BM Condition").Copy After:=Sheets(Sheets.Count)
ActiveSheet.Name = "BM Condition" & Sheets.Count - 1
Range("E14:E33,I14:I33,M14:M33").ClearContents
For Each sh In ActiveSheet.Shapes
sh.Delete
Next sh
strtSh.Select
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub
This is the macro I am using. I have very limited VBA experience and am not finding google very helpful. Could someone recommend a fix for my buttons not copying over?
EDIT: I forgot to mention that when manually copying the buttons remain. I am not sure why this is.
As FunThomas mentioned, I've tried and tested the following without any errors:
Sub CanD()
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Dim sh As Shape, strtSh As Worksheet
Set strtSh = ActiveSheet
Sheets("BM Condition").Copy After:=Sheets(Sheets.Count)
ActiveSheet.Name = "BM Condition" & Sheets.Count - 1
Range("E14:E33,I14:I33,M14:M33").ClearContents
strtSh.Select
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub

hiding selected worksheets without for loop

I would like to hide some worksheets, all at once, without using for loop. The reason for this is a big number of worksheets, so my macro works a while.
Do you have any ideas how can I improve the running time of this macro?
You can just record a macro of selecting the first sheet, and then select the last sheet with Shift. Then you right-click and Hide.
Sheets(Array("Sheet2", "Sheet3", "Sheet4")).Visible = False
Or by index
Sheets([{2, 3, 4}]).Visible = False
Note that you can not unhide more than one sheet at a time.
To add a custom view with all sheets visible:
For Each ws In Sheets
ws.Visible = True
Next
ActiveWorkbook.CustomViews.Add "All" ' you can change the name
Then, to un-hide all sheets:
ActiveWorkbook.CustomViews("All").Show
To un-hide the sheets faster, you can try disabling some of the events and calculation:
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
For Each ws In Sheets: ws.Visible = True: Next
Application.ScreenUpdating = True
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
Sub HideSheets()
Dim sSheets() As String
sSheets = Split("Sheet1,Sheet2,Sheet3", ",")
Worksheets(sSheets).Visible = xlHidden
End Sub

Delete worksheet in Excel using VBA

I have a macros that generates a number of workbooks. I would like the macros, at the start of the run, to check if the file contains 2 spreadsheets, and delete them if they exist.
The code I tried was:
If Sheet.Name = "ID Sheet" Then
Application.DisplayAlerts = False
Sheet.Delete
Application.DisplayAlerts = True
End If
If Sheet.Name = "Summary" Then
Application.DisplayAlerts = False
Sheet.Delete
Application.DisplayAlerts = True
End If
This code is returning an error:
run time error #424, object required.
I probably have the wrong formatting, but if there is an easier way to do this, it would be very useful.
Consider:
Sub SheetKiller()
Dim s As Worksheet, t As String
Dim i As Long, K As Long
K = Sheets.Count
For i = K To 1 Step -1
t = Sheets(i).Name
If t = "ID Sheet" Or t = "Summary" Then
Application.DisplayAlerts = False
Sheets(i).Delete
Application.DisplayAlerts = True
End If
Next i
End Sub
NOTE:
Because we are deleting, we run the loop backwards.
Try this code:
For Each aSheet In Worksheets
Select Case aSheet.Name
Case "ID Sheet", "Summary"
Application.DisplayAlerts = False
aSheet.Delete
Application.DisplayAlerts = True
End Select
Next aSheet
You could use On Error Resume Next then there is no need to loop through all the sheets in the workbook.
With On Error Resume Next the errors are not propagated, but are suppressed instead. So here when the sheets does't exist or when for any reason can't be deleted, nothing happens. It is like when you would say : delete this sheets, and if it fails I don't care. Excel is supposed to find the sheet, you will not do any searching.
Note: When the workbook would contain only those two sheets, then only the first sheet will be deleted.
Dim book
Dim sht as Worksheet
set book= Workbooks("SomeBook.xlsx")
On Error Resume Next
Application.DisplayAlerts=False
Set sht = book.Worksheets("ID Sheet")
sht.Delete
Set sht = book.Worksheets("Summary")
sht.Delete
Application.DisplayAlerts=True
On Error GoTo 0
Worksheets("Sheet1").Delete
Worksheets("Sheet2").Delete
try this within your if statements:
Application.DisplayAlerts = False
Worksheets(“Sheetname”).Delete
Application.DisplayAlerts = True

Re-setting all option buttons at once

I have written a code for re-setting all option button on one click but its giving an error, "object doesnt support the property or matter".
Sub Add_New_Record()
Dim i As Integer
For i = 1 To 30
With Sheets("Form")
'-- unlock the worksheet
.Unprotect
.OptionButton(i).Value = False
'-- lock the worksheet
'.Protect
.Activate
.Range("Q12").Select
End With
Next i
End Sub
Can anyone please suggest me how to fix the code and make the value of all option buttons "false" at one.
I know how to do it individually like:
Sub Add_New_Record()
With Sheets("Form")
'-- unlock the worksheet
.Unprotect
.OptionButton1.Value = False
'-- lock the worksheet
'.Protect
.Activate
.Range("Q12").Select
End With
End Sub
but since I have too many buttons, the code will get really long and inefficient.
Thanks for your help and time.
First, the With statement should be before the For loop. And it should be .OptionButtons. Try this one.
Sub Add_New_Record()
Dim i As Integer
With Sheets("Form")
.Unprotect
For i = 1 To 30
.OptionButtons(i).Value = False
Next i
.Protect
End With
End Sub
Loop through all the OLEObjects on a particular sheet and if it is an optionbutton then set it to false.
For i = 1 To ActiveSheet.OLEObjects.Count
If TypeName(ActiveSheet.OLEObjects(i).Object) = "OptionButton" Then
ActiveSheet.OLEObjects(i).Object = False
End If
Next i
Embedding this snippet in your code:
Sub Add_New_Record()
With Sheets(1)
.Unprotect
For i = 1 To .OLEObjects.Count
If TypeName(.OLEObjects(i).Object) = "OptionButton" Then
.OLEObjects(i).Object = False
End If
Next i
.Protect
.Range("Q12").Select
End With
End Sub
Read more about OLEObjects here

VBA excel 2010 working with sheets names and delete blanc sheets

I would like to know why VBA is telling me that the SUB function is missing while trying to write this code. The purpose should be that when the sheet is called NVT the code should skip any operation and go to the next sheet that will be activated (in the next command). In the end of this operation I should delete every blanc sheet(s) where there is no "specific name" or "NVT" filled in.
The formula is working good without this option. I have no problem saving this code and no problem with the formula itselve. Any suggestion is welcom.. I don't believe this threat has been posted yet.
Please let me know if you need additional information. The original code is verry long and would like just a indication how to sove this issue.Thanx in advace for who will answer tis threat.
Sub Printtabs()
' Print
ThisWorkbook.Activate
If ThisWorkbook.Sheets(7) = ("NVT") Then Skip
If ThisWorkbook.Sheets(7) = ("NAME SPECIFIC 1") Then
'process formula
End If
If Thisworkbook.Sheets (8) = ("NVT) Then Skip
If Thisworkbook.Sheets (8) = ("NAME SPECIFIC 2") Then
'process formula
End If
'then I should find the way to delete every "blanc" sheets in this workbook (becouse I skipped before and there will be blanc sheets) and save
End Sub
You don't need to use .Activate. You can directly work with the sheets. Also when deleting sheets and switching off events, always use proper error handling.
Is this what you are trying?
Dim ws As Worksheet
Sub Printtabs()
On Error GoTo Whoa
For Each ws In ThisWorkbook.Worksheets
If ws.Name = "NAME SPECIFIC 1" Then
'~~> Process Formula
ElseIf ws.Name = "NAME SPECIFIC 2" Then
'~~> Process Formula
Else
If ws.Name <> "NTV" And WorksheetFunction.CountA(ws.Cells) = 0 Then
Application.DisplayAlerts = False
ws.Delete
Application.DisplayAlerts = True
End If
End If
Next ws
LetsContinue:
Application.DisplayAlerts = True
Exit Sub
Whoa:
MsgBox Err.Description
Resume LetsContinue
End Sub
So, I figured out how to delete the blanc sheets I believe.
Only the issue with sheetsnames is remaining.
This part of code I will run at the end of all processed formulas.
Hopely somebody could help me out....
Dim ws As Worksheet
For Each ws In Worksheets
If WorksheetFunction.CountA(ws.Cells) = 0 Then
Application.DisplayAlerts = False
ws.Delete
Application.DisplayAlerts = True
End If
Next ws