且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

无法删除工作表

更新时间:2023-12-02 08:11:04

Sub Change()

Dim wb As Excel.Workbook
Set wb = ActiveWorkbook 'ThisWorkbook

Dim ws As Excel.Worksheet
Set ws = wb.Sheets("FileSearch Results")

Dim rng As Range
Set rng = ws.UsedRange

Dim cPaths As Integer
cPaths = rng.Column

Dim i As Integer
i = rng.row

'Dim oExcel As Excel.Application ***CHANGED***
'Set oExcel = New Excel.Application ***CHANGED***

'Dim oWB As Workbook ***CHANGED***

Dim komm As Excel.Worksheet
Dim sh1 As Excel.Worksheet

Do While i < 2
    Dim pth As String
    pth = ws.Cells(i, cPaths)
    'Set oWB = oExcel.Workbooks.Open(pth) ***CHANGED***

    Workbooks.Open (pth) '***ADDED***

    Set sh1 = ActiveWorkbook.Worksheets("Sheet1") 'oWB.Worksheets("Sheet1") ***CHANGED***
    With sh1.UsedRange
        .Value = .Value
    End With

    Set komm = ActiveWorkbook.Worksheets("Kommentar") 'oWB.Worksheets("Kommentar") ***CHANGED***
    Application.DisplayAlerts = False
    komm.Delete
    Application.DisplayAlerts = True

    ActiveWorkbook.Close savechanges:=True 'oWB.Close savechanges:=True ***CHANGED***
    i = i + 1

Loop

End Sub

现在这将打开工作簿并在前台删除工作表,而不是调用Excel的新实例并在后台删除工作表.这就是为什么文件保持锁定的原因,因为未被代码关闭的新实例仍保留该文件.

This now opens the workbook and deletes the sheet in the foreground rather than invoking a new instance of Excel and deleting the sheet in the background. This is why the file stays locked, as the new instance which isn't closed by the code, still holds it.