我无法让我的宏运行AfterSave
或BeforeClose
事件。
我将一张工作表导出到一个 .csv 文件,当我将此宏链接到一个按钮时,它已经可以很好地与下一个代码一起使用:
Sub CopyToCSV()
Worksheets("LastLots").UsedRange.Rows("1:5").Calculate
ThisWorkbook.Save
Dim MyPath As String
Dim MyFileName As String
'The path and file names:
MyPath = "D:\Data\PW\2018\"
MyFileName = "LastLots-exported"
'Makes sure the path name ends with "\":
If Not Right(MyPath, 1) = "\" Then MyPath = MyPath & "\"
'Makes sure the filename ends with ".csv"
If Not Right(MyFileName, 4) = ".csv" Then MyFileName = MyFileName & ".csv"
'Copies the sheet to a new workbook:
Sheets("LastLots").Copy
'The new workbook becomes Activeworkbook:
With ActiveWorkbook
Application.DisplayAlerts = False
'Saves the new workbook to given folder / filename:
.SaveAs Filename:= _
MyPath & MyFileName, _
FileFormat:=xlCSV, _
CreateBackup:=False
'Closes the file
.Close False
Application.DisplayAlerts = True
End With
End Sub
上面的代码在一个模块中。正如我所说,当链接到一个按钮并按下该按钮时,它工作得很好。但我希望它在用户保存文件时运行。为此,我将下一个代码放入ThisWorkbook
:
Private Sub Workbook_AfterSave(ByVal Success As Boolean)
If Success = True Then
Call CopyToCSV
End If
End Sub
我尝试了各种方法,例如将宏的代码放在AfterSave
-event 中,Application.EnableEvents
并在调用前后禁用/启用,CopyToCSV
但对我没有任何作用......
有人有建议吗?我疯了,我在谷歌上找到的每个主题都说要把代码放进去ThisWorkbook
,但已经这样做了。