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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46967251/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 10:54:44  来源:igfitidea点击:

VBA - Create new sheet and rename it

excelvbaexcel-vbadate

提问by Youiee

I am trying to insert a new sheet and then rename it to the current month and year just with one button. For some extra information: I'm planning on removing this button a bit later on so that it will be automatic.

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

Private Sub CommandButton1_Click()

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

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

End Sub

回答by jivko

This will do it:

这将做到:

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

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

回答by Subodh Tiwari sktneer

Consider to have some kind of error handling to check if the sheet you are adding already exists otherwise if somehow you run the same code again, it will give you an error and a new default sheet will also be added at the same time which I don't think what you would want.

考虑进行某种错误处理以检查您添加的工作表是否已经存在,否则如果以某种方式再次运行相同的代码,它会给您一个错误,并且还会同时添加一个新的默认工作表,我不这样做不要想你会想要什么。

Also it's a good practice to declare all the variables used in the code.

此外,声明代码中使用的所有变量也是一个好习惯。

You should try it like this...

你应该像这样尝试......

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

回答by Karl Kristjansson

This should work for you:

这应该适合你:

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