在特定时间运行VBA代码

时间:2015-05-06 14:11:29

标签: excel vba

我在这个网站上发现以下代码“将Excel文件保存为CSV”有任何方法可以帮助你我可以在特定时间(每晚11:00)自动运行此代码,并保存文件名称为当前日期(hr2015-05-05),任何帮助将不胜感激。感谢

Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
Dim Sourcewb As Workbook
Dim Destwb As Workbook
Dim TempFileName As String

With Application
    .ScreenUpdating = False
    .EnableEvents = False
    .DisplayAlerts = False
End With

Set Sourcewb = ActiveWorkbook
TempFileName = Sourcewb.FullName + ".csv"

'Copy the sheet to a new workbook
ActiveSheet.Copy
Set Destwb = ActiveWorkbook

'Save the new workbook and close it
With Destwb
    .SaveAs Filename:=TempFileName, FileFormat:=xlCSV, ConflictResolution:=xlLocalSessionChanges
    .Close SaveChanges:=False
End With

With Application
    .ScreenUpdating = True
    .EnableEvents = True
    .DisplayAlerts = True
End With
End Sub

修改固定代码问题

1 个答案:

答案 0 :(得分:7)

我会这两种方式之一。

一个是通过Windows任务调度程序。您将在哪里设置打开Excel并以该方式运行的任务。见http://www.mrexcel.com/forum/excel-questions/302970-task-scheduler-vbulletin-script-auto-open-excel.html

或者

使用代码

Application.OnTime TimeValue("23:00:00"), SUBNAMEHERE

SUBNAMEHERE更改为代码所在的子站点。不确定它是否会通过

运行beforesave部分

EDIT添加了具有文件名

的代码

TempFileName = Sourcewb.FullName + ".csv"更改为

TempFileName = Sourcewb.FullName & " hr" & format(now,"YYYY-MM-DD") & ".csv"