我有一个包含CSV数据源和数据透视表的Excel文件,我想自动刷新所有数据源和数据透视表,并在打开excel文件时将一个数据透视表导出为CSV。
我尝试了以下代码,但此代码在刷新数据之前导出CSV文件。
请帮助解决方案。提前谢谢。
Private Sub Workbook_Open()
ThisWorkbook.RefreshAll
Run "Macro1"
End Sub
Sub Macro1()
Dim ws As Worksheet, newWb As Workbook
Dim SaveToDirectory As String
SaveToDirectory = "C:\Macro\"
Application.ScreenUpdating = False
For Each ws In Sheets(Array("locationwise"))
ws.Copy
Set newWb = ActiveWorkbook
With newWb
.SaveAs SaveToDirectory & ws.Name, xlCSV
.Close (False)
End With
Next ws
Application.ScreenUpdating = True
Application.DisplayAlerts = False
End Sub
答案 0 :(得分:2)
一个简单的DoEvents
应该可以做到! ;)
试试这个:
Private Sub Workbook_Open()
ThisWorkbook.RefreshAll
DoEvents
Run "Macro1"
End Sub
如果不是,只需在DoEvents
:
Application.Wait(Now + TimeValue("0:00:05"))
这将暂停执行代码,这里持续5秒!
如果您想在修改特定范围后启动保存部分,请将该代码放入工作表模块中:
Private Sub Worksheet_Change(ByVal Target As Range)
If Application.Intersect(Target, Me.Range(Rg_To_Check)) Is Nothing Then
'Not in range
Else
'In range to check
Run "Macro1"
End If
End Sub
摆脱Run "Macro1"
事件中的Workbook_Open()
。
另外,请注意,因为您的最后一行是Application.DisplayAlerts = False
,之后您将不会收到提醒,您应该像这样使用它:
Sub Macro1()
Dim ws As Worksheet, newWb As Workbook
Dim SaveToDirectory As String
SaveToDirectory = "C:\Macro\"
Application.DisplayAlerts = False
Application.ScreenUpdating = False
For Each ws In Sheets(Array("locationwise"))
ws.Copy
Set newWb = ActiveWorkbook
With newWb
.SaveAs SaveToDirectory & ws.Name, xlCSV
.Close (False)
End With
Next ws
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub