问题
I know how to make marcos but during school he never taught me everything to do with them, mainly with the Dim. My questions is how to I make a marco that will rename all my sheets expect for the first four.
Sub RenameSheet()
Dim rs As Worksheet
For Each rs In Sheets
rs.Name = rs.Range("D5")
Next rs
End Sub
Works for every sheet but I dont want to be renaming every sheet. My first four are Documentation, Summarry, RONATemplate, KaycanTemplate. Which I want to leave has is. I cant really just put those names in cell D5 to make it work where its a template, and it will mess up my other marcos.
回答1:
To change every sheet after the 4th use the index property of sheets in an if statement:
Sub RenameSheet()
Dim rs As Worksheet
For Each rs In Sheets
If rs.Index > 4 Then
rs.Name = rs.Range("D5")
End If
Next rs
End Sub
回答2:
You could create kind of a blacklist with and check if rs.Name
is one of the names you do not want to change or you could access the sheets by index.
i.e.
For i = 5 to Worksheets.Count
Worksheets(i).Name = rs.Range("D5")
Next
回答3:
First option is to use different kind of loop which iterates based on sheet index/number. Here is the code running only for Worksheets Collection
:
Sub RenameSheet()
Dim rs As Long
For rs = 5 To Worksheets.Count
Worksheets(rs).Name = Worksheets(rs).Range("D5")
Next rs
End Sub
Your loop starts as of 5th of worksheet and runs until the last one.
The other option is to exclude all sheets with names which you have mentioned in your question. In that situation you could run this macro:
Sub RenameSheet()
Dim rs As Worksheet
For Each rs In Sheets
if rs.name <> "Summary" And rs.Name <> "RONATemplate" and rs.Name <> "KeycanTemplate" Then
rs.Name = rs.Range("D5")
end if
Next rs
End Sub
However, keep in mind that all conditional checks like rs.Name <> "Summary"
are case sensitive therefore you need to put appropriate names within code including upper- and lower- cases. Or you could use UCase
function to compare to capitalized names like:
if UCase(rs.Name) <> "SUMMARY" And UCase(rs.Name) <> "RONATEMPLATE" And Ucase(rs.Name) <> "KEYCANTEMPLATE" Then
I would suggest to use second type of improved procedure. If you change the order of your sheets (e.g. move first sheet into 6th position) you will get unexpected results running first For i=1
loop. There is not such problem running second type of loop/subroutine.
来源:https://stackoverflow.com/questions/16750124/renaming-sheets-in-macro-without-renaming-first-four-sheets