excel vba宏另存为csv-每小时

时间:2018-10-15 19:35:24

标签: excel vba excel-vba excel-2016

我正在研究一个简单的vba代码。 我有一本xlsm工作簿,里面有一些纸...

我想每小时将所有工作表导出为csv。

这就是我已经准备好的(但它没有保存...)

Sub ExportSheetsToCSV()
Application.DisplayAlerts = False
Dim xWs As Worksheet
Dim xcsvFile As String
For Each xWs In Application.ActiveWorkbook.Worksheets
    xWs.Copy
    xcsvFile = CurDir & "\" & xWs.Name & ".csv"
    Application.ActiveWorkbook.SaveAs Filename:=xcsvFile, _
    FileFormat:=xlCSV, CreateBackup:=False
    Application.ActiveWorkbook.Saved = True
    Application.ActiveWorkbook.Close
Next
Application.DisplayAlerts = True
Call RefreshDataEachHour
End Sub

在此工作簿模块中:

Public Sub RefreshDataEachHour()

Application.OnTime Now + TimeValue("01:00:00"), "ExportSheetsToCSV"

End Sub

当我删除此行时:Application.DisplayAlerts = False 导出工作正常,但不是每小时都可以,并且我必须在有关文件格式(公式丢失)的提示消息中选中“是”

我很乐意将其完成...

2 个答案:

答案 0 :(得分:0)

也许可以使用CurDir来代替ThisWorkbook.Path。如果您希望此功能每小时运行一次,并且您也在同一台PC上工作,那么CurDir可以/将根据您在做什么而改变。

Sub ExportSheetsToCSV()
    Application.DisplayAlerts = False
    Dim xWs As Worksheet, wb As Workbook
    Dim xcsvFile As String
    For Each xWs In Application.ActiveWorkbook.Worksheets
        xWs.Copy
        Set wb = ActiveWorkbook
        xcsvFile = ThisWorkbook.Path & "\" & xWs.Name & ".csv"
        wb.SaveAs Filename:=xcsvFile, _
            FileFormat:=xlCSV, CreateBackup:=False
        wb.Close False 'don't save
    Next
    Application.DisplayAlerts = True
    Call RefreshDataEachHour
End Sub

答案 1 :(得分:0)

好的,

代码完美运行... 它只需要是一个模块,而不是ThisWorkbook中的宏。

万一有人需要它: 只需添加一个模块并使用以下脚本即可:

Public Sub RefreshDataEachHour()

    Application.OnTime Now + TimeValue("00:00:10"), "Book1.xlsm!ExportSheetsToCSV"

    End Sub
    Sub ExportSheetsToCSV()
    Application.DisplayAlerts = False
    Dim xWs As Worksheet
    Dim xcsvFile As String
    For Each xWs In Application.ActiveWorkbook.Worksheets
        xWs.Copy
        xcsvFile = CurDir & "\" & xWs.Name & ".csv"
        Application.ActiveWorkbook.SaveAs Filename:=xcsvFile, _
        FileFormat:=xlCSV, CreateBackup:=False
        Application.ActiveWorkbook.Saved = True
        Application.ActiveWorkbook.Close
    Next
    Application.DisplayAlerts = True
    Call RefreshDataEachHour
    End Sub