Excel:VBA脚本错误运行时错误'2147417848(80010108)'

时间:2018-04-09 16:01:10

标签: excel vba excel-vba

使用以下VBA代码运行两个单独的过程,我通过单独的按钮调用这些过程。 根据我运行它们的顺序,我得到运行时错误:

  • DeleteSheets1 =没有错误GetSheets - 没有错误DeleteSheets1 + GetSheets - 错误!
  • DeleteSheets1,(关闭并重新打开Excel),GetSheets - NoError
  • GetSheets,DeleteSheets1 - 无错误
  • GetSheets,GetSheets,GetSheets - 没有错误
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会阻止错误,我想知道它是基于内存还是我的删除子没有清除所需内容?

1 个答案:

答案 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运行时没有错误。