簡體   English   中英

創建復制的 Excel 工作表拋出 424 錯誤

[英]Created copied Excel Worksheet throws 424 error

目標是創建在當前月份和年份中重命名的復制工作表。 正在工作簿中創建復制的工作表,但是為工作表提供了默認名稱。 我錯過了什么?

Private Sub Button3_Click()

Dim wb As Workbook
Dim ws As Worksheet
Dim nowMonth As Integer, nowYear As Integer

Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual

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

Set wb = ActiveWorkbook

On Error Resume Next

Set ws = wb.Sheet(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 = ActiveSheet.Copy(after:=wb.Sheets(wb.Sheets.Count))
    ws.Name = nowMonth & ", " & nowYear

End If

Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic

End Sub

問題出在Set ws = ActiveSheet.Copy(after:=wb.Sheets(wb.Sheets.Count))中,因為它試圖同時CopySet ,這有點太多了。 將條件中的代碼更改為:

If Not ws Is Nothing Then
    MsgBox "something"
    Exit Sub
Else:
    Set ws = ActiveSheet
    ws.Copy after:=wb.Sheets(wb.Sheets.Count)
    wb.Worksheets(wb.Sheets.Count).Name = nowMonth & ", " & nowYear
End If

In general, avoid using Active and Select in VBA - How to avoid using Select in Excel VBA .

Worksheet.Copy令人失望地沒有返回對創建工作表的引用。 相反,它具有向工作簿添加新工作表並激活它的副作用。

所以在運行Worksheet.Copy之后, ActiveSheet就是新創建的工作表。

ActiveSheet.Copy after:=wb.Sheets(wb.Sheets.Count)
ActiveSheet.Name = nowMonth & ", " & nowYear

現在,此代碼令人困惑/具有誤導性,因為看起來這兩個語句使用相同的 object 限定,但它們不是。

不清楚的是,為什么以及如何保證ActiveSheet是要復制的正確工作表; 我們正在處理ActiveWorkbook ,我們並不關心哪個工作表處於活動狀態。

我建議將副本制作為明確的工作表:

Dim sourceSheet As Worksheet
Set sourceSheet = wb.Sheets(wb.Sheets.Count)

sourceSheet.Copy after:=sourceSheet '<~ new sheet becomes ActiveSheet
ActiveSheet.Name = nowMonth & ", " & nowYear

現在一切都很清楚了。

暫無
暫無

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

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