【问题标题】:Excel VBA - How to run a macro inside a moduleExcel VBA - 如何在模块内运行宏
【发布时间】:2016-06-17 17:45:35
【问题描述】:

我有一个包含客户和产品数据的送货单电子表格。我想要一个按钮,而不是单击时询问“您要保存和打印吗?”。 我已经为要保存的文件记录了一个宏,当模块单独运行时它工作正常,但是当它全部放在下面的代码中时,我收到以下错误:'编译错误:预期的结束子'。 else 部分本身也运行良好。如何解决此错误并让代码运行?谢谢

Private Sub CommandButton1_Click()
MsgBox "Do you want to Save as well as Print?", vbYesNo
If answer = vbYes Then
Sub mac_SaveNote()
ChDir "C:\Users\User\Desktop\DeliveryNotes"
ActiveWorkbook.SaveAs Filename:="C:\Users\User\Desktop\DeliveryNotes\" & Range("A11"), _
    FileFormat:=xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False
End Sub
Else
Sheets("Note 1").PrintOut , Copies:=2   'prints 2 copies of note1
Range("A11:J16").ClearContents          'clears customer data
Range("A18:I42").ClearContents          'clears product data
End If
End Sub

【问题讨论】:

    标签: vba excel if-statement macros


    【解决方案1】:

    两种方式:

    将 sub 移出第一个并简单地调用它:

    Private Sub CommandButton1_Click()
    MsgBox "Do you want to Save as well as Print?", vbYesNo
    If answer = vbYes Then
    
         mac_SaveNote
    
    Else
        Sheets("Note 1").PrintOut , Copies:=2   'prints 2 copies of note1
        Range("A11:J16").ClearContents          'clears customer data
        Range("A18:I42").ClearContents          'clears product data
    End If
    End Sub
    
    Sub mac_SaveNote()
    ChDir "C:\Users\User\Desktop\DeliveryNotes"
    ActiveWorkbook.SaveAs Filename:="C:\Users\User\Desktop\DeliveryNotes\" & Range("A11"), _
        FileFormat:=xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False
    End Sub
    

    或者直接运行代码并删除 Sub 部分

    Private Sub CommandButton1_Click()
    MsgBox "Do you want to Save as well as Print?", vbYesNo
    If answer = vbYes Then
    
        ChDir "C:\Users\User\Desktop\DeliveryNotes"
        ActiveWorkbook.SaveAs Filename:="C:\Users\User\Desktop\DeliveryNotes\" & Range("A11"), _
            FileFormat:=xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False
    
    Else
        Sheets("Note 1").PrintOut , Copies:=2   'prints 2 copies of note1
        Range("A11:J16").ClearContents          'clears customer data
        Range("A18:I42").ClearContents          'clears product data
    End If
    End Sub
    

    【讨论】:

    • 错误已消失,但文档尚未保存。我不知道这是否与文件名是一个在代码执行后删除其内容的单元格有关。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-05-09
    • 1970-01-01
    • 1970-01-01
    • 2018-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多