VBA For Loop Only Altering One Sheet - vba

I'm trying to alter the values in a range of cells for specifically named worksheets only.
The workbook I am editing has around 95 sheets, and I only want to change the sheets with the period actual information (named P1W1, P1W2 etc, up to P12W5).
When i execute the below it only alters the first sheet and then exits the macro.
Any help is much appreciated
Option Explicit
Public Sub periodclear()
Dim ws As Worksheet
Dim r As Range
On Error Resume Next
Set r = Range("c10:i30")
For Each ws In Worksheets
If ws.Name Like ("P#W#") Or ws.Name Like ("P##W#") Then
r.Value = ""
End If
Next ws
End Sub

Try this. Your r was defined only in terms of one sheet so needs to be brought inside the loop.
Public Sub periodclear()
Dim ws As Worksheet
For Each ws In Worksheets
If ws.Name Like ("P#W#") Or ws.Name Like ("P##W#") Then
ws.Range("c10:i30").ClearContents
End If
Next ws
End Sub

Related

VBA How to fix: "Property or method is not supported with this object" when cell securing in multiple sheets

So bassicaly I want to secure a specific range within every sheet (same range always applies).
Code:
Sub desecure()
For x = 1 To ActiveWorkbook.Sheets.Count
ActiveWorkbook.Sheets(x).Range("C7:P16").Protect Password:="30713"
Next
End Sub
Sub secure()
For x = 1 To ActiveWorkbook.Sheets.Count
ActiveWorkbook.Sheets(x).Range("C7:P16").Protect Password:="30713"
Next
End Sub
It always give the error stated in the question. Anyone knows how to fix this? (or a alternative)
You can't protect a range - you set ranges to either "locked" or "unlocked" and then protect the whole sheet
To begin with, all cells are set to locked, but as the spreadsheet isn't protected this has no affect. In your case (assuming you want to be able to change other cells), you would need to unlock every other cell, lock the range you want to prevent changes in, and then protect the sheet. So
Sub secure()
dim ws as worksheet 'i change this line - typo
For each ws in worksheets
ws.cells.locked=false
ws.Range("C7:P16").locked=true
ws.Protect Password:="30713"
next ws
End Sub
Sub Desecure
dim ws as worksheet
For each ws in worksheets
ws.unprotect "30713"
Next ws
End Sub

Deleting Specific Worksheets

I am attempting to delete all worksheets in my workbook except for the two titled: "main" and "dataset". My current code seems to simply delete the last two worksheets.
Option Explicit
Option Base 1
Public Sub DeleteWS()
Dim mySheet As String, mySheet2 As String, ws As Worksheet
mySheet = "main"
mySheet2 = "Dataset"
For Each ws In Worksheets
If ws.Name <> mySheet Or ws.Name <> mySheet2 Then
ActiveWindow.SelectedSheets.Delete
Else
Exit Sub
End If
Next
End Sub
Change this line:
ActiveWindow.SelectedSheets.Delete
to this:
ws.Delete
to fix your If statement
Use And in your If, not Or
and keep in mind that capitalization and extra spaces both matter too in a comparison like that.
I would use something more like this:
If Trim$(UCase$(ws.Name)) <> Trim$(UCase$(mySheet)) And _
Trim$(UCase$(ws.Name)) <> Trim$(UCase$(mySheet2)) Then
You could also go like this:
Option Explicit
Option Base 1
Public Sub DeleteWS()
Dim ws As Worksheet
For Each ws In Worksheets
If InStr(ws.Name, “main,Dataset”) = 0 Then ws. Delete
Next
End Sub

How to copy the sheet name to a column on the same sheet?

I am using this code:
Function wrksht() as Variant
wrksht = Application.Caller.Parent.Name
End function
I am continuously being thrown
run time error '424' object not found
I have a workbook with several sheets, each having a date on it.
I want to populate the first column on every sheet with its sheet name.
Function wrksht() as String
wrksht = ActiveSheet.Name
End function
UPDATE
Function DoIt()
Dim sh As Worksheet
For Each sh In ActiveWorkbook.Sheets
sh.Range("A1") = sh.Name
Next
End Function
The above will work, but I have an easier solution:
=MID(CELL("filename",A1),FIND("]",CELL("filename",A1))+1,255)
Paste this value (it is a formula, not VBA code) into the cell you wish to populate with the sheet name, and it will magically appear.
Try this
Sub my_macro
On error resume next
Dim ws As Worksheet
For Each ws In ActiveWorkbook.Sheets
ws.Range("A1") = ws.Name
Next
End sub

VBA Code to cycle through worksheets starting with a specific sheet (index 3)

I need to cycle through sheets of index 3 tip last sheet and run a code. I tried something like this but its doesn't work.
If (ws.sheetIndex > 2) Then
With ws
'code goes here
End With
End If
I did a search but don't find a solution to this problem. Help would be much appreciated.
I also tried:
Dim i As Long, lr As Long
Dim ws As Worksheet
Windows("Book1").Activate
With ActiveWorkbook
Set ws = .Worksheets("index")
For i = 3 To 10
'code goes here
Next i
End With
You can try the following, which iterates over all worksheets in your workbook and only "acts" for worksheets with index 3 or above.
Dim sheet As Worksheet
For Each sheet In ActiveWorkbook.Worksheets
If sheet.Index > 2 Then
' Do your thing with each "sheet" object, e.g.:
sheet.Cells(1, 1).Value = "hi"
End If
Next
Note that this doesn't put a hard limit on the number of sheets you have (10 or whatever), as it will work with any number of worksheets in your active workbook.
EDIT
If you want the code to run on worksheets with names "Sheet" + i (where i is an index number from 3 onwards), then the following should help:
Dim sheet As Worksheet
Dim i As Long
For i = 3 To ActiveWorkbook.Worksheets.Count
Set sheet = ActiveWorkbook.Worksheets(i)
If sheet.Name = "Sheet" & i Then
' Do your thing with each "sheet" object, e.g.:
sheet.Cells(2, 2).Value = "hi"
End If
Next i
Of course, this means that the names of your worksheets need to always follow this pattern, so it's not best practice. However, if you're sure the names are going to stay like this, then it should work well for you.
Try excluding first and second sheet using name:
Public Sub Sheets3andUp()
Dim ws As Worksheet
Dim nameOfSheet1 As String
Dim nameOfSheet2 As String
nameOfSheet1 = "Sheet1"
nameOfSheet2 = "Sheet2"
For Each ws In ActiveWorkbook.Worksheets
If ws.Name <> nameOfSheet1 And ws.Name <> nameOfSheet2 Then
'Code goes here
Debug.Print ws.Name
End If
Next ws
End Sub
Note that the user can reorder the sheets in the Worksheets Collection, so it is better to refer to the sheets by CodeName (which the user cannot change), and exclude by CodeName the sheets to be skipped, as here:
Public Sub TestLoop()
On Error GoTo ErrHandler
Dim ws As Worksheet, s As String
For Each ws In Worksheets
If ws.CodeName <> "Sheet2" Then
s = s & vbNewLine & ws.CodeName
End If
Next ws
s = "WorksheetList (except Sheet2:" & vbNewLine & vbNewLine & s
MsgBox s, vbOKOnly, "Test"
EndSUb:
Exit Sub
ErrHandler:
Resume EndSUb
End Sub
If I drag Sheet 3 to precede Sheet1, the MsgBox outputs:
WorksheetList (except Sheet2:
Sheet3
Sheet1

How to add a list of specific worksheets to the list in ComboBox VBA

I found a way to add all of the worksheets in the workbook into the list of the ComboBox on the UserForm, which is done with use of the following code
Private Sub UserForm_Initialize()
Dim ws As Worksheet
For Each ws In Worksheets
cmbSheet.AddItem ws.Name
Next ws
End Sub
My problem is that I only need to add some specific worksheets and not all of them. For example my user will select specific sheet and by clicking "Continue" button should end up on the selected worksheet to continue his/her task. My workbook holds several worksheets, some of which are used to output data (Reports) and some worksheets contain so called templates, which I want my user (only those) to be able to select from the ComboBox I have talked above.
Can you guys help me please?
Private Sub UserForm_Initialize()
Dim ws As Worksheet
For Each ws In Worksheets
if ws.Name like "*Template" then cmbSheet.AddItem ws.Name
Next ws
End Sub
perhaps you could use a naming convention for the worksheets?
if the reports you want the user to select all have the word temmplate in their name you could do something like this:
Private Sub UserForm_Initialize()
Dim ws As Worksheet
For Each ws In Worksheets
if instr(lcase(ws.name),"template")<>0 then
cmbSheet.AddItem ws.Name
end if
Next ws
End Sub