在我的命名活动EXCEL表单上,我输入了一个少于32个字符的字符串,比如说单元格A1
。
我想使用A1
中的字符串重命名工作表。我过去曾使用过VBA,但有一段时间没用过。
如果有人可以建议在单击单元格A1时执行此操作的宏,我会很高兴。是否有任何字符不能在A1中(我想要〜和下划线)?
答案 0 :(得分:1)
将此代码粘贴到相关的Sheet对象(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
答案 1 :(得分:0)
对于完整的流程,我建议
使用此代码
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