我试图通过在每个工作表中使用单元格值来重命名我的大型Excel中的选项卡。问题是,我想重命名具有相同名称的多个选项卡,这是不允许的。我可以添加1,然后是2等,但我不知道该怎么做。
例如,如果3张中的单元格值是俄亥俄州,那么选项卡将是Ohio1,Ohio2,Ohio3。
每张纸的名称应该是A1中的值,但我想说明重复的名称。
执行此操作而不考虑相同名称的vba代码是:
Sub Worksheet_SelectionChange()
Dim ws As Worksheet
For Each ws In Sheets
ws.Activate
ActiveSheet.Name = Range("a1").Value
Next ws
End Sub
答案 0 :(得分:0)
Sub Worksheet_SelectionChange()
Dim ws As Worksheet
Dim i As Integer
i = 1
On Error GoTo fixName
For Each ws In Me.Worksheets
ws.name = ws.Range("A1").Value
Next ws
Exit Sub
fixName:
ws.name = ws.Range("A1").Value & i
i = i + 1
End Sub
答案 1 :(得分:0)
Sub RenameTabs()
Dim ws As Worksheet, wsName$, wsCount%, dict ' $ is short for " As String" and % for " As Integer"
Set dict = CreateObject("Scripting.Dictionary")
For Each ws In Sheets
wsName = ws.Range("A1").Value
wsCount = IIf(dict.Exists(wsName), dict(wsName) + 1, 1)
dict(wsName) = wsCount
If wsCount = 1 Then
ws.Name = wsName
Else
If wsCount = 2 Then Sheets(wsName).Name = wsName & 1 ' optional to rename the previous Ohio sheet to Ohio1
ws.Name = wsName & wsCount
End If
Next ws
End Sub