使用以下VBA代码运行两个单独的过程,我通过单独的按钮调用这些过程。 根据我运行它们的顺序,我得到运行时错误:
Sub DeleteSheets1()
Dim xWs As Worksheet
Application.ScreenUpdating = False
Application.DisplayAlerts = False
For Each xWs In Application.ActiveWorkbook.Worksheets
If xWs.Name <> "Master" Then
xWs.Delete
End If
Next
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub
-------------------------------------------------
Sub GetSheets()
Dim path As String, Filename As String, sheet, Awb As Workbook
path = "mypathhere"
Filename = Dir(path & "*.xlsx")
Do While Filename <> ""
Workbooks.Open Filename:=path & Filename, ReadOnly:=True
Set Awb = ActiveWorkbook
For Each sheet In Awb.Worksheets
sheet.Copy After:=ThisWorkbook.Sheets(1)
Next sheet
Workbooks(Filename).Close
Filename = Dir()
Loop
End Sub
鉴于关闭并重新打开Excel会阻止错误,我想知道它是基于内存还是我的删除子没有清除所需内容?
答案 0 :(得分:0)
好的,我找到了一个可行的解决方案
Sub Reopen()
'Sets as active, saves and reopens workbook
Dim wb As Excel.Workbook
Set wb = ThisWorkbook
Dim pth As String
pth = wb.FullName
Application.DisplayAlerts = False
Application.OnTime Now + TimeValue("00:00:01"), Application.Workbooks.Open(pth)
wb.Close (True)
Application.DisplayAlerts = True
End Sub
在DeleteSheets1
之后立即调用上述程序; Excel保存并重新打开工作簿。这会清除缓存,这意味着GetSheets
运行时没有错误。