Vba Excel在工作簿的最后一张工作表后添加带有代码的工作表
我每月从一张名为“模板”的表格中添加一张表格,并将其命名为“月-年”。这一切都很好,但它会将新的工作表放在“模板”工作表旁边。我希望它在工作簿的最后一张工作表之后添加新工作表。我将其更改为Shhet count,但出现了一个错误。你能帮忙吗? 这是我的密码Vba Excel在工作簿的最后一张工作表后添加带有代码的工作表,vba,Vba,我每月从一张名为“模板”的表格中添加一张表格,并将其命名为“月-年”。这一切都很好,但它会将新的工作表放在“模板”工作表旁边。我希望它在工作簿的最后一张工作表之后添加新工作表。我将其更改为Shhet count,但出现了一个错误。你能帮忙吗? 这是我的密码 Sub CopySheet() Dim MySheetName As String 'MySheetName = ActiveCell.Text 'OR MySheetName = InputBox("
Sub CopySheet()
Dim MySheetName As String
'MySheetName = ActiveCell.Text
'OR
MySheetName = InputBox("Enter a Sheet Name!")
'check a value has been entered
If MySheetName = "" Then
MsgBox "No sheet name was entered, ending!"
Exit Sub
Else
'================================================
'Check there are no invalid sheet name characters
'================================================
If ValidSheetName(MySheetName) Then
Sheets.Add.Name = "Template"
Worksheets("Template").Move After:=Worksheets(Worksheets.Count)
Else
MsgBox "There is an invalid character in the sheet name!"
End If
End If
End Sub
Function ValidSheetName(ByVal sheetName As String) As Boolean
'========================================
'check a sheetname for invalid characters
'========================================
Dim arrInvalid As Variant
Dim i As Long
arrInvalid = Array("/", "\", "[", "]", "*", "?", ":")
For i = LBound(arrInvalid) To UBound(arrInvalid)
If InStr(1, sheetName, arrInvalid(i), vbTextCompare) Then
ValidSheetName = False
Exit Function
End If
Next
ValidSheetName = True
End Function
可以通过以下方式指定新添加图纸的位置:
ThisWorkbook.Sheets.Add after:=ThisWorkbook.Sheets(<index>)
您可以考虑使用外部模板文件从预格式化/预填充模板(.xLTX)中添加新的页:
为了检查输入的工作表名称的有效性,您可以简单地让Excel完成它的工作,同时为以下异常做好准备:On Error Resume Next
Activesheet.Name = MySheetName
If Err.Number = 1004 Then ' invalid name (wrong char, existing sheetname, zero length name, whatever)
MsgBox "Invalid or existing sheet name!
Else
Err.Raise Err.Number ' other error
End If
On Error Goto 0
注:
On Error
子句,它们非常有用,但在错误使用时很容易误导您所以你有一张你正在复制的模板表?如果是这样,请执行
工作表(“模板”)。复制时间:=工作表(Sheets.Count)
。然后ActiveSheet.Name=“新名称”
。复制模板,将其移动到末尾,然后重命名为所需的名称。如果起始工作表索引为0,则最后一个工作表索引可能为工作表。计数-1?另一方面,如果你能分享你得到的错误,那就更好了。谢谢你。这澄清了我试图实现的目标,并发挥了作用perfectly@user3795705欢迎那么请接受我的回答,表明它是有用的。
ThisWorkbook.Sheets.Add after:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count), Type:=<full spec of template file>
Activesheet.Name="something"
On Error Resume Next
Activesheet.Name = MySheetName
If Err.Number = 1004 Then ' invalid name (wrong char, existing sheetname, zero length name, whatever)
MsgBox "Invalid or existing sheet name!
Else
Err.Raise Err.Number ' other error
End If
On Error Goto 0