就像我在评论中提到的那样,重命名工作表并不是那么简单。你必须检查很多东西。
我的假设
- 您的工作簿中有 5 张工作表;
Sheet1
, Sheet2
,和Sheet3
_Sheet4
Sheet5
- 当您更改 中的单元格时
Sheet5
,根据更改的单元格,Sheets1-4's
名称会更改
- 我假设当
A1
更改时,Sheet1
被重命名。当A2
更改,Sheet2
被重命名等等......
逻辑
- 使用
Worksheet_Change
event 捕获对cell A1
、A2
或A3
A4
- 使用 Sheet CodeName 更改名称
- 检查工作表名称是否有效。工作表名称不能包含任何这些字符
\ / * ? [ ]
- 检查您是否已经有一张带有要用于重命名的名称的工作表
- 如果一切都很好,那就去替换
代码
请参阅此示例。此代码位于Sheet5
代码区域中。
Dim sMsg As String
Private Sub Worksheet_Change(ByVal Target As Range)
Dim wsName As String
On Error GoTo Whoa
sMsg = "Success"
Application.EnableEvents = False
If Not Target.Cells.CountLarge > 1 Then
If Not Intersect(Target, Range("A1")) Is Nothing Then
wsName = Left(Target, 31)
RenameSheet [Sheet1], wsName
ElseIf Not Intersect(Target, Range("A2")) Is Nothing Then
wsName = Left(Target, 31)
RenameSheet [Sheet2], wsName
ElseIf Not Intersect(Target, Range("A3")) Is Nothing Then
wsName = Left(Target, 31)
RenameSheet [Sheet3], wsName
ElseIf Not Intersect(Target, Range("A4")) Is Nothing Then
wsName = Left(Target, 31)
RenameSheet [Sheet4], wsName
End If
End If
MsgBox sMsg
Letscontinue:
Application.EnableEvents = True
Exit Sub
Whoa:
MsgBox Err.Description
Resume Letscontinue
End Sub
'~~> Procedure actually renames the sheet
Sub RenameSheet(ws As Worksheet, sName As String)
If IsNameValid(sName) Then
If sheetExists(sName) = False Then
ws.Name = sName
Else
sMsg = "Sheet Name already exists. Please check the data"
End If
Else
sMsg = "Invalid sheet name"
End If
End Sub
'~~> Check if sheet name is valid
Function IsNameValid(sWsn As String) As Boolean
IsNameValid = True
'~~> A sheet name cannot contain any of these Characters \ / * ? [ ]
For i = 1 To Len(sWsn)
Select Case Mid(sWsn, i, 1)
Case "\", "/", "*", "?", "[", "]"
IsNameValid = False
Exit For
End Select
Next
End Function
'~~> Check if the sheet exists
Function sheetExists(sWsn As String) As Boolean
Dim ws As Worksheet
On Error Resume Next
Set ws = ThisWorkbook.Sheets(sWsn)
On Error GoTo 0
If Not ws Is Nothing Then sheetExists = True
End Function
截屏