Hi,
I can see where you got the idea for your name.
On a code sheet most code is grouped in procedures - either subs or functions. Very little code is permitted "outside" such procedures. This is the compile error you are getting.
A procedure must be declared and ended. Like this:
Sub YourSubsName()
End Sub
You can choose a name of your liking, more or less. Avoid unusual characters and don't use spaces. The brackets at the end are necessary. The End Sub will be inserted by VB automatically.
All your code must be between the declaration line and the end.
All your declarations should be made at the top of your code. Having a Dim statement somewhere in the middle might actually work, but not always and, anyway, it isn't good practice. So, this is what you get:
- Code: Select all
Public Sub AutoNameWs()
Dim NextName as String
Dim Ws as Worksheet
Dim Dt as Date
For Each Ws in Worksheets
If Cdate(Ws.Name) > Dt Then Dt = Cdate(Ws.Name)
Next Ws
NextName = Format(Dt + 7, "mm-dd-yy")
Set Ws = Worksheets.Add (Before:=Sheets(1))
Ws.Name = NextName
End Sub
Note that I added the word Public before the Sub declaration. Procedures are Public by default. So it isn't necessary, but code is easier to read if you don't have to read what is missing in addition to what is there. I added the Dt variable for you because if you don't first create it you can't very well use it to create the NextName. Finally, note how "brackets" are created by indenting blocks of code. That also serves the purpose of making the code easier to read.
I have inserted the code in the ThisWorkbook code sheet in the attached workbook. The dates produced by the code aren't what you would expect. That is because my system works with dd.mm.yy dates. Therefore it can't understand the dates formatted as mm-dd-yy. Once you have a workbook where all dates were produced and written by the same system the problem will go away. It will come back though, if you allow a difference between the day-month sequence in your Regional Settings and the format of the date in the tabs - as the attached workbook demonstrates.
You do not have the required permissions to view the files attached to this post.
Have a great day!
Sisyphus
I do this for "honour and country" - much less of the latter, actually.
If I helped you, award points, plenty of them.
If I bored you, deduct points for being too long-winded. (I know, :lol)