簡體   English   中英

Excel 在工作簿中的最后一個工作表之后添加帶有代碼的工作表

[英]Excel add sheet with code after last sheet in Workbook

我每個月從名為“模板”的工作表中添加一張工作表,並將其命名為“月年”。 一切正常,但它將新工作表放在“模板”工作表旁邊。 我希望它在工作簿中的最后一張工作表之后添加新工作表。 我將其更改為 Shhet count 但出現錯誤。 你能幫我嗎? 這是我的代碼。

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>)

其中<index>是從 1 到張數的數字。

這個在工作簿的末尾添加了一張新表:

ThisWorkbook.Sheets.Add after:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count)

您可以考慮使用外部模板文件從預格式化/預填充模板 (.xltx) 添加新工作表:

ThisWorkbook.Sheets.Add after:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count), Type:=<full spec of template file>

模板文件只能包含 1 張紙。

工作表添加將隱式激活工作表,因此您可以在添加后為其命名

Activesheet.Name="something"

為了檢查輸入的工作表名稱的有效性,您可以簡單地讓 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

筆記:

  1. 雖然在語法上是正確的,但有時我在從模板添加新工作表並在一個命令中重命名時遇到問題,這就是為什么我建議分兩步單獨進行:首先添加然后重命名
  2. 請注意On Error子句,它們非常有用,但在使用不當時很容易誤導您。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM