我想创建一个宏来获取单元格中的值,并使用此值重命名工作表。我只希望将单元格值的一部分用作工作表名称。
例如,在单元格A1中,它表示" John Doe" ...我希望宏命名该表单" Doe,J。"。我该怎么做?
我已经知道如何根据整个单元格命名工作表。
Sub RenameSheet()
Dim rs As Worksheet
For Each rs In Sheets
rs.Name = rs.Range("B5")
Next rs
End Sub
答案 0 :(得分:0)
您需要先使用名称解析字符串,然后检查表单是否已存在(如果已存在,请添加计数器,并确保不要使用相同名称命名两个表单)。像这样:
Sub RenameSheet()
'VARIABLES DECLARATION
Dim rs As Worksheet
Dim new_name As String, tmp_new_name As String
Dim counter As Integer: counter = 0
Dim counter1 As Integer: counter1 = 1
Dim allNames As Object
'CODE
Set allNames = CreateObject("Scripting.Dictionary")
For Each rs In Sheets
'FIRST, LET'S PARSE THE NAME "LAST NAME" + ", " + "NAME INITIAL" + "."
new_name = Split(rs.Range("B5"), " ")(1) + ", " + Left(Split(rs.Range("B5"), " ")(0), 1) + "."
'CHECK IF IT EXISTS
If allNames.Exists(new_name) Then
'ADD A COUNTER "(N)" UNTIL IT DOESN'T EXIST ANYMORE
tmp_new_name = new_name
Do While allNames.Exists(tmp_new_name) <> False
tmp_new_name = new_name & " (" & counter1 & ")"
counter1 = counter1 + 1
Loop
counter1 = 1
new_name = tmp_new_name
End If
'RENAME
rs.name = new_name
counter = counter + 1
'KEEP THE NAME STORED IN MEMORY (INTO THE DICTIONARY)
allNames.Add rs.name, counter
Next rs
End Sub