在我命名的活动 EXCEL 表上,我在 cell 中放置了一个少于 32 个字符的字符串A1
。
我想使用字符串A1
来重命名工作表。我过去使用过 VBA,但有一段时间没有使用过。
如果有人可以建议在单击单元格 A1 时执行此操作的宏,我会很高兴。是否有任何字符不能出现在 A1 中(我想要 ~ 和下划线)?
将此代码粘贴到相关的工作表对象(VBA 编辑器)中。
请注意,您还可以使用事件,例如双击。
在选择活动工作表的单元格“A1”时,工作表名称将成为单元格“A1”包含的值。
Option Explicit
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim sSheet_Name As String
If Target = ActiveSheet.Range("A1") Then
sSheet_Name = ActiveSheet.Range("A1").Value
ActiveSheet.Name = sSheet_Name
End If
End Sub
对于一个完整的过程,我会推荐
使用此代码
View Code
代码由右键单击单元格 A1 触发
Private Sub Worksheet_BeforeRightClick(ByVal Target As Range, Cancel As Boolean)
Dim rng1 As Range
Dim StrNew As String
Dim objRegex As Object
Dim blTest As Boolean
Dim ws As Worksheet
Set rng1 = Intersect(Range("A1"), Target)
If rng1 Is Nothing Then Exit Sub
StrNew = rng1.Value
Set objRegex = CreateObject("vbscript.regexp")
With objRegex
.Pattern = "[\/\\\?\*\]\[]"
.Global = True
blTest = .test(StrNew)
StrNew = .Replace(StrNew, vbNullString)
End With
On Error Resume Next
Set ws = Sheets(StrNew)
On Error GoTo 0
If ws Is Nothing Then
If Len(StrNew) > 0 And Len(StrNew) < 32 Then
ActiveSheet.Name = StrNew
MsgBox "Sheet name updated to " & StrNew & vbNewLine & IIf(blTest, "Invalid characters were removed", vbNullString)
Else
MsgBox "Sheetname of " & StrNew & " is either empty or too long", vbCritical
End If
Else
MsgBox "Sheet " & StrNew & " already exists", vbCritical
End If
End Sub