从模板创build新的电子表格
我正在开发代码,无论何时将文本input到列A中的任何行中,都会创build模板电子表格的副本。电子表格需要在input文本后命名。
目前我有下面的代码,问题是它没有命名我input的文本后的新电子表格。
代码如下:
Private Sub Worksheet_Change(ByVal Target As Range) Dim wsNew As Worksheet If Target.Cells.Count > 1 Then Exit Sub On Error Resume Next If Not Intersect(Target, Range("A1:A10")) Is Nothing Then Set wsNew = Sheets(Target.Text) If wsNew Is Nothing Then Worksheets("Template").Copy After:=Worksheets(Worksheets.Count) End If 'name new sheet code here End If End Sub
喜欢这个:
Private Sub Worksheet_Change(ByVal Target As Range) Dim wsNew As Worksheet If Target.Cells.Count > 1 Then Exit Sub On Error Resume Next If Not Intersect(Target, Range("A1:A10")) Is Nothing Then Set wsNew = Sheets(Target.Text) If wsNew Is Nothing Then Worksheets("Template").Copy After:=Worksheets(Worksheets.Count) End If 'name new sheet Worksheets(Worksheets.Count).Name = Target.Text End If End Sub
编辑:
用户可以清空A1:A10
的单元格,这将创build一个名为“ Template(2) ”的新选项卡。 你也应该检查:
If Len(Target.Cells.Text) = 0 Then Exit Sub
我build议像这样build立基于所需名称的模板的工作表 – 但是在testing和清理build议的工作表名称首先为无效字符
Private Sub Worksheet_Change(ByVal Target As Range) Dim wsNew As Worksheet Dim strSht As String If Target.Cells.Count > 1 Then Exit Sub If Not Intersect(Target, Range("A1:A10")) Is Nothing Then On Error Resume Next Set wsNew = Sheets(Target.Text) On Error GoTo 0 If wsNew Is Nothing Then If ValidSheetName(Target.Value) Then strSht = Target.Value Else strSht = CleanSheetName(Target.Value) End If End If Worksheets("Template").Copy After:=Worksheets(Worksheets.Count) ActiveSheet.Name = strSht End If End Sub
string清洁代码1
Function ValidSheetName(strIn As String) As Boolean Dim objRegex As Object Set objRegex = CreateObject("vbscript.regexp") objRegex.Pattern = "[\<\>\*\\\/\?|]" ValidSheetName = Not objRegex.test(strIn) End Function
string清洁代码2
Function CleanSheetName(strIn As String) As String Dim objRegex As Object Set objRegex = CreateObject("vbscript.regexp") With objRegex .Global = True .Pattern = "[\<\>\*\\\/\?|]" CleanSheetName = .Replace(strIn, "_") End With End Function