打开时自动将Excel工作表另存为csv

时间:2018-04-17 08:27:42

标签: excel vba excel-vba

我正在尝试编写一个宏,以便在Excel文件打开时自动将Excel工作表另存为csv。这是我正在使用的代码。请帮忙。

Option Explicit

Sub Test()

Dim wbkExport As Workbook
Dim shtToExport As Worksheet

ActiveWorkbook.RefreshAll
Set shtToExport = ThisWorkbook.Worksheets("Sheet1")     
Set wbkExport = Application.Workbooks.Add
shtToExport.Copy Before:=wbkExport.Worksheets(wbkExport.Worksheets.Count)
Application.DisplayAlerts = False                     
wbkExport.SaveAs Filename:="C:\Users\Kennedy\Desktop\Alinta\Testcsv\test1.csv", FileFormat:=xlCSV
Application.DisplayAlerts = True
wbkExport.Close SaveChanges:=True
End Sub

1 个答案:

答案 0 :(得分:0)

您只需将以下代码放在ThisWorkbook模块上。

Private Sub Workbook_Open()
    Dim wbkExport As Workbook
    Dim shtToExport As Worksheet
    Application.ScreenUpdating = False
    ActiveWorkbook.RefreshAll
    Set shtToExport = ThisWorkbook.Worksheets("Sheet1")
    Set wbkExport = Application.Workbooks.Add
    shtToExport.Copy Before:=wbkExport.Worksheets(wbkExport.Worksheets.Count)
    Application.DisplayAlerts = False
    wbkExport.SaveAs Filename:=Environ("UserProfile") & "\Desktop\Alinta\Testcsv\test1.csv", FileFormat:=xlCSV
    Application.DisplayAlerts = True
    wbkExport.Close SaveChanges:=True
    Application.ScreenUpdating = True
End Sub