VBA - 创建新工作表并重命名

时间:2017-10-27 03:53:36

标签: excel vba excel-vba date

我正在尝试插入新工作表,然后只用一个按钮将其重命名为当前月份和年份。对于一些额外的信息:我打算稍后删除此按钮,以便它是自动的。

Private Sub CommandButton1_Click()

  nowMonth = Month(Now)
  nowYear = Year(Now)

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

End Sub

3 个答案:

答案 0 :(得分:3)

这样做:

nowMonth = Month(Now)
nowYear = Year(Now)

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

答案 1 :(得分:3)

考虑使用某种错误处理来检查您添加的工作表是否已经存在,否则如果您以某种方式再次运行相同的代码,它将给您一个错误,同时还会添加一个新的默认工作表我不会想你想要的东西。

同样,声明代码中使用的所有变量也是一种很好的做法。

你应该这样试试......

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

答案 2 :(得分:1)

这应该适合你:

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