VBA – 创build新工作表并重新命名

我试图插入一个新的表格,然后用一个button重新命名为当前的月份和年份。 对于一些额外的信息:我打算稍后删除此button,以便它会自动。

Private Sub CommandButton1_Click() nowMonth = Month(Now) nowYear = Year(Now) ActiveWorkbook.Sheets.Add After:=Worksheets(Worksheets.Count)Name = "nowMonth & , & nowYear) End Sub 

这将做到这一点:

 nowMonth = Month(Now) nowYear = Year(Now) ActiveWorkbook.Sheets.Add After:=Worksheets(Worksheets.Count) ActiveWorkbook.Sheets(Worksheets.Count).Name = nowMonth & "," & nowYear 

这应该为你工作:

 Private Sub sheet() nowMonth = Month(Now) nowYear = Year(Now) ActiveWorkbook.Sheets.Add(After:=Worksheets(Worksheets.Count)).Name = nowMonth & "," & nowYear End Sub 

考虑有一些error handling来检查你正在添加的工作表是否已经存在,否则如果你再次运行相同的代码,它会给你一个错误,一个新的默认工作表也会被同时添加,我不会不要想你想要什么。

声明代码中使用的所有variables也是一个好习惯。

你应该这样试试…

 Private Sub CommandButton1_Click() Dim wb As Workbook Dim ws As Worksheet Dim nowMonth As Integer, nowYear As Integer nowMonth = Month(Now) nowYear = Year(Now) Set wb = ActiveWorkbook On Error Resume Next Set ws = wb.Sheets(nowMonth & ", " & nowYear) On Error GoTo 0 If Not ws Is Nothing Then MsgBox "The Sheet called " & nowMonth & ", " & nowYear & " already exists in the workbook.", vbExclamation, "Sheet Already Exists!" Exit Sub Else Set ws = wb.Sheets.Add(after:=wb.Sheets(wb.Sheets.Count)) ws.Name = nowMonth & ", " & nowYear End If End Sub