2015-12-04 48 views
-1

我對VBA很新穎。我有一個包含20個工作表的電子表格。有一個宏,每15分鐘運行一次,它將在工作表5,10,15和20上顯示數據。我希望能夠每隔15分鐘以.csv格式自動將這些數據保存在這些工作表中。每15分鐘自動將某些Excel表格(xlsm文件)保存爲.csv

該電子表格被稱爲'Events.xlsm';我想要保存的工作表是事件總數,事件總數(2),事件總數(3)和事件總數(4)。我曾試圖根據本網站上的其他示例保存其中一個工作表。不知道我是否在正確的軌道上。

Sub SaveWorksheetsAsCsv() 

Dim WS As Excel.Worksheet 
Dim SaveToDirectory As String 

Dim CurrentWorkbook As String 
Dim CurrentFormat As Long 

CurrentWorkbook = ThisWorkbook.Events 
CurrentFormat = ThisWorkbook.xlsm 
' Store current details for the workbook 
SaveToDirectory = "S:\test\" 
For Each WS In Day Event.Worksheets 
Sheets(WS.Event Total).Copy 
ActiveWorkbook.SaveAs Filename:=SaveToDirectory & ThisWorkbook.Events & "-" & WS.Event Total & ".csv", FileFormat:=xlCSV 
ActiveWorkbook.Close savechanges:=False 
ThisWorkbook.Activate 

Next 

Application.DisplayAlerts = False 
ThisWorkbook.SaveAs Filename:=CurrentWorkbook, FileFormat:=CurrentFormat 
Application.DisplayAlerts = True 
' Temporarily turn alerts off to prevent the user being prompted 
' about overwriting the original file. 

End Sub 
+0

歡迎來到VBA社區!請編輯您的問題,包括您迄今在這項工作中所取得的成就。 – Jeeped

+0

Excel宏是基於事件的,它不能每15分鐘自動觸發一次,除非yr宏保持運行並且永不停止。 –

+0

@EricK。 - 具有循環和結束時間語句的'Application.OnTime'可以每15分鐘運行一次宏。 –

回答

0

你到了那裏。有一堆東西需要清理。我只是重構代碼併爲你評論一些代碼,而不是寫一篇長篇教程。

這裏有一個警告: CSV文件是一個非常具體和獨特格式。這意味着,每個文件只能有一張,沒有特殊的格式或類似的東西。如果有,則需要在保存csv之前將其清理乾淨。

Sub SaveWorksheetsAsCsv() 

Dim WS As Worksheet 
Dim SaveToDirectory As String 

' Store current details for the workbook 
SaveToDirectory = "S:\test\" 

For Each WS In ThisWorkbook.Worksheets 

    If Left(WS.Name, 10) = "Event Total" Then 'evaluate if its a sheet that needs to be saved 

     Dim wbCopy As Workbook 
     WS.Copy 
     Set wbCopy = ActiveWorkbook 

     'Application.DisplayAlerts = False 'turn this on once you are sure it will save the CSV correctly, even with a warning prompt 
     With wbCopy 
      .SaveAs Filename:=SaveToDirectory & ThisWorkbook.Name & "-" & WS.Name & ".csv", FileFormat:=xlCSV 
      .Close savechanges:=False 
     End With 
     'Application.DisplayAlerts = True 

    End If 

Next 

ThisWorkbook.Save 'a simple save will do here. no need to overwrite the workbook unless you want to 

End Sub 
+0

感謝@Scott Holtzman。 WS.Name之後的「10」是指什麼? –

+0

查看'左'功能。它從'WS.Name'返回10個左邊的字符或者任何參數是 –

+0

如果這對你@JamesAndrews有效,請標記爲已回答。 –

相關問題