在保存

时间:2015-11-18 20:08:06

标签: excel-vba vba excel

我是VBA的新手,我有一个工作簿,我用它来生成采购订单。 在ThisWorkbook中,我有以下代码。

Private Sub Workbook_open()
Sheet1.[g6] = Sheet1.[g6] + 1
Sheet1.[b4] = ""
Sheet1.[c10] = ""
Sheet1.[a17] = ""
Sheet1.[a20:h35] = ""
Sheet1.CommandButton2.Enabled = False
Sheet1.CommandButton1.Enabled = False
End Sub

我还在Sheet1上附加了代码。有没有办法在commandbutton2_click()中删除Workbook_open编码?工作簿通过电子邮件发送并妥善保存,但每次重新打开时,它都会重复workbook_open()并清除数据。由于批准过程,保存的工作簿仍需要启用宏。

Private Sub CommandButton2_Click()
  If IsEmpty(Sheet1.Range("B4")) Then
        MsgBox "Please fill Highlighted cells before closing."
        Cancel = True
    End If
    If IsEmpty(Sheet1.Range("C10")) Then
        MsgBox "Please fill Highlighted cells before closing."
        Cancel = True
    End If
    If IsEmpty(Sheet1.Range("A17")) Then
        MsgBox "Please fill Highlighted cells before closing."
        Cancel = True
    End If


Dim FileName As String
 Dim Path As String

Application.DisplayAlerts = False

Path = "\\COSRVR1\Data\Purchase orders\"
 FileName = Sheet1.Range("G6").Value & ".xlsm"

ThisWorkbook.SaveAs Path & FileName, xlOpenXMLWorkbookMacroEnabled

CommandButton2.Visible = False

Dim olapp As Outlook.Application
Set olapp = CreateObject("outlook.application")

Dim olmail As Outlook.MailItem
Set olmail = olapp.CreateItem(olMailItem)
olmail.To = Sheet1.Range("a8")
olmail.Subject = "Approval needed_" & Sheet1.Range("g6")
olmail.Attachments.Add ActiveWorkbook.FullName
olmail.send
ActiveWorkbook.Close

End Sub


Private Sub Worksheet_Change(ByVal Target As Range)

    If Sheet1.Range("i38").Value > 1999 Then
        CommandButton2.Enabled = True
    Else
        CommandButton2.Enabled = False
End If
    If Sheet1.Range("i38").Value = 0 Then
        CommandButton1.Enabled = False
    Else
    End If
    If Sheet1.Range("i38").Value < 2000 Then
        CommandButton1.Enabled = True
    Else
        CommandButton1.Enabled = False
End If
End Sub

1 个答案:

答案 0 :(得分:0)

尝试添加此内容:

With ThisWorkbook.VBProject.VBComponents("ThisWorkbook").CodeModule
    .DeleteLines 1, .CountOfLines
End With