我遇到过类似的问题,AfterSave不会为人们运行,但是他们的答案仍未解决我的情况,在这种情况下,AfterSave似乎无法运行的原因是我的BeforeSave代码。这两套代码彼此独立地正常工作,但是我无法让它们在同一工作簿中运行。
该代码当前写在“ ThisWorkbook”中,只需在保存之前将文件的保存名称设置为单元格值,然后在保存后将文本文件中的数字加1即可更新文本文件。 / p>
根据我的研究,问题似乎与Cancel
或Application.EnableEvents
有关。
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
Application.EnableEvents = False
Dim sFile As String
sFile = Range("B3").Value & ".xlsm"
Application.Dialogs(xlDialogSaveAs).Show sFile
ActiveSheet.ExportAsFixedFormat _
Type:=xlTypePDF
'Application.Dialogs(xlDialogSaveAs).Show(arg1:=ThisWorkbook.Sheets("Sheet1").Range("B3").Value)
Application.EnableEvents = True
Cancel = True
End Sub
Private Sub Workbook_AfterSave(ByVal Success As Boolean)
Application.EnableEvents = True
If Success Then
'Open the text file to overwrite the number in the text file
Open "\\digitalsense.com.au\FileShares\Public\_Purchase Orders\PO_Number_Generator.txt" For Output As #1
'Overwrite the number with the PO number
Print #1, Cells(1, 2)
'Close the text file
Close #1
End If
End Sub
我应该能够单击“保存”或按正常方式保存,并且文件名字段已用单元格B3
中的文本预先填充。保存后,我的文本文件需要通过将文本文件中的数字增加1来更新。
答案 0 :(得分:0)
在BeforeSave
中,您要设置Cancel = True
-这会取消“保存”操作,因此不会触发AfterSave
事件。
编辑:也许是这样的
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
Dim sFile As String
sFile = ActiveSheet.Range("B3").Value & ".xlsm"
Application.EnableEvents = False
'did the file get saved?
If Application.Dialogs(xlDialogSaveAs).Show(sFile) Then
UpdateSequenceNumber ActiveSheet.Cells(1, 2).Value
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF
End If
Application.EnableEvents = True
Cancel = True
End Sub
Sub UpdateSequenceNumber(newVal)
Open "\\digitalsense.com.au\FileShares\Public\_Purchase Orders\PO_Number_Generator.txt" For Output As #1
Print #1, newVal
Close #1
End Sub
答案 1 :(得分:0)
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
Dim sFile As String
sFile = ActiveSheet.Range("B3").Value & ".xlsm"Application.EnableEvents = False
'did the file get saved?
If Application.Dialogs(xlDialogSaveAs).Show(sFile) Then
UpdateSequenceNumber ActiveSheet.Cells(1, 2).Value
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF
End If
Application.EnableEvents = True
Cancel = True End SubSub UpdateSequenceNumber(newVal)
Open "\\digitalsense.com.au\FileShares\Public\_Purchase Orders\PO_Number_Generator.txt" For Output As #1
Print #1, newVal
Close #1
结束子