从数据中清除当前文件的副本

时间:2015-07-30 10:04:34

标签: excel vba excel-vba copy

有工作流程可以填写表单并在您完成后将其邮寄。邮件的方法会将当前工作表作为附件发送,但它应该直接创建工作表的新副本,从中删除所有数据。

我可以清除当前的工作表,但那是错的,因为我需要清除 new 表。我已经阅读过关于在其他工作簿上运行宏的内容,但它无法运行宏。什么是最好的解决方案?

Sub SendData_Click()
    If MsgBox("Sure to send?", vbYesNo, "Confirm") = vbYes Then
        ' Save current sheet
        ActiveWorkbook.Save

        ' Send the current file
        Mail_ActiveSheet

        ' Mark this sheet as sent
        Worksheets("Data").Range("B6").Value = True

        ' Create a new emptied version
        Create_New_Copy

        MsgBox "Your data is sent"
    End If
End Sub

Sub Create_New_Copy()
    Dim Wb As Workbook
    Dim NewFileName As String
    Dim FileExtStr As String
    Dim FilePath As String

    Set Wb = ActiveWorkbook
    NewFileName = "FileNameHere " & Format(DateAdd("d", 1, Now), "yyyy-mm-dd")
    FileExtStr = "." & LCase(Right(Wb.Name, Len(Wb.Name) - InStrRev(Wb.Name, ".", , 1)))
    FilePath = ActiveWorkbook.Path & "\" & NewFileName & FileExtStr

    ' # This is the problem, how to clear only the new file??
    ' Clear_Sheet_Invoices

    ' Save this sheet as the new file
    Wb.SaveCopyAs FilePath
End Sub

Sub Clear_Sheet_Invoices()
    Dim Ws As Worksheet
    Set Ws = Worksheets("MyDataSheet")

    ' Remove all contents
    Ws.Range("B2:F999").ClearContents

    ' Mark the "sent" flag for the new sheet to False
    Worksheets("Data").Range("B6").Value = False
End Sub

您可能会注意到,我正在使用ActiveWorkbook.SaveCopyAs创建副本,并且我有一个Sub Clear_Sheet_Invoices可以清除所有必需的数据。如何在新文件上运行此子文件?

我原本想将MyDataSheet复制到新工作表,清除数据表,保存新文件并复制工作表。在打开文件时,我检查是否存在纸张的副本,我将删除该纸张。是的,该死的丑陋,应该有更好的方法吗? ;)

1 个答案:

答案 0 :(得分:0)

您可以更改Clear_Sheet_Invoices()的定义,使其需要Workbook类型的参数,并在此工作簿中清除工作表“MyDataSheet”。

然后,您可以调用此sub并将新创建的工作簿作为参数传递。

以下是您需要更改以实现它的代码:

Sub Clear_Sheet_Invoices(Wb As Workbook)
    Dim Ws As Worksheet
    Set Ws = Wb.Worksheets("MyDataSheet")

    ' Remove all contents
    Ws.Range("B2:F999").ClearContents

    ' Mark the "sent" flag for the new sheet to False
    Wb.Worksheets("Data").Range("B6").Value = False

End Sub
Sub Create_New_Copy()
    Dim Wb As Workbook
    Dim NewWb As Workbook
    Dim NewFileName As String
    Dim FileExtStr As String
    Dim FilePath As String

    Set Wb = ActiveWorkbook
    NewFileName = "FileNameHere " & Format(DateAdd("d", 1, Now), "yyyy-mm-dd")
    FileExtStr = "." & LCase(Right(Wb.Name, Len(Wb.Name) - InStrRev(Wb.Name, ".", , 1)))
    FilePath = ActiveWorkbook.Path & "\" & NewFileName & FileExtStr

    ' Save this sheet as the new file
    Wb.SaveCopyAs FilePath
    Set NewWb = Excel.Workbooks.Open(FilePath)


    ' # This is the problem, how to clear only the new file??
    Call Clear_Sheet_Invoices(NewWb)
    Call NewWb.Close(True)

End Sub

方法SendData_Click不需要任何更改。