excel 将工作表导出为新工作簿,但先删除按钮,但也会生成错误

whhtz7ly  于 2023-03-13  发布在  其他
关注(0)|答案(1)|浏览(102)

我编写了一个绑定到按钮的宏,用于将excel工作表导出到新工作簿并保存。宏在保存之前删除了所有按钮。宏工作正常,工作表生成并保存,但在关闭之前,我得到了一个错误,我不知道为什么!

Sub Export_IssuesLog()

Dim answer As Integer
Dim PathName As String

answer = MsgBox("Do you want to export the issues log?" _
& Chr(13) & Chr(13) & Chr(10) & "Note: This macro automatically overwites versions with the same Revision Number. Please ensure the revision number is updated correctly.", vbQuestion + vbYesNo)

  If answer = vbYes Then
  
        PathName = ThisWorkbook.Path & "\" & Range("Proj_no").Value & "_" & Range("Client_short").Value & "_" & Range("Facility_short").Value & "_IssuesLog_REV-" & Range("B4").Value & ".xlsx"
        
        ActiveSheet.Copy
        
        For Each btn In ActiveSheet.Shapes
            If btn.AutoShapeType = msoShapeStyleMixed Then btn.Delete
        Next
        
        ActiveWorkbook.SaveAs Filename:=PathName
        ActiveWorkbook.Close SaveChanges:=False
        
  Else
    Exit Sub
    
  End If

End Sub

如果我删除这段代码(它确实成功地删除了按钮),宏将完美地工作。

For Each btn In ActiveSheet.Shapes
            If btn.AutoShapeType = msoShapeStyleMixed Then btn.Delete
        Next

如果我包含了这段代码,它给我的错误是在ActiveWorkbook.SaveAs行上。它给我一个运行时错误“1004”-对象“_workbook”的方法“SaveAs”失败。
问题是,它确实保存了工作簿!我不知道我做错了什么!

7cjasjjr

7cjasjjr1#

引用对象

  • 使用Option Explicit
  • 尝试一次引用一个对象,即使用变量。
Option Explicit

Sub ExportIssuesLog()

    Dim swb As Workbook: Set swb = ThisWorkbook ' workbook containing this code
    ' Make sure the workbook is active, or the ranges will fail.
    If Not swb Is ActiveWorkbook Then swb.Activate
    If Not TypeOf ActiveSheet Is Worksheet Then Exit Sub ' not a worksheet
    Dim sws As Worksheet: Set sws = ActiveSheet
    
    Dim dPath As String: dPath = swb.Path & "\" & Range("Proj_no").Value _
        & "_" & Range("Client_short").Value & "_" _
        & Range("Facility_short").Value & "_IssuesLog_REV-" & Range("B4").Value
    
    Dim Answer As Long
    Answer = MsgBox("Do you want to export the issues log?" _
        & Chr(13) & Chr(13) & Chr(10) & "Note: This macro automatically " _
        & "overwites versions with the same Revision Number. " _
        & "Please ensure the revision number is updated correctly.", _
        vbQuestion + vbYesNo)
    If Answer = vbNo Then Exit Sub ' canceled
    
    sws.Copy
    
    Dim dwb As Workbook: Set dwb = Workbooks(Workbooks.Count)
    Dim dws As Worksheet: Set dws = dwb.Sheets(1)
        
    Dim shp As Shape
    For Each shp In dws.Shapes
        If shp.AutoShapeType = msoShapeStyleMixed Then shp.Delete
    Next shp
    
    Application.DisplayAlerts = False ' overwrite without conpfirmation
        dwb.SaveAs Filename:=dPath
    Application.DisplayAlerts = True
    dwb.Close SaveChanges:=False
    
    MsgBox "Issues Log exported.", vbInformation
    
End Sub

相关问题