我对VBA很新。我有一个包含20个工作表的电子表格。有一个宏每15分钟运行一次,显示工作表5,10,15和20上的数据。我希望能够每隔15分钟以.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 :(得分:0)
你有点到达那里。有很多东西需要清理。我只是重构了代码并为你评论了一些代码,而不是编写一个很长的教程。
此处有一个警告: CSV文件是一种非常具体且独特的 flat 格式。这意味着,每个文件只能有一个工作表,没有特殊的格式或类似的东西。如果有,您需要在保存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