Excel corruption with VBA sorting records

Sel*_*rac 1 excel vba

I have an Excel file with a macro that filters records. After running the macro I save and close the file. Once I open the file again it says that the file has been corrupted:

Excel found unreadable content in '[filename].xls'.
Do you want to recover the contents of this workbook?
If you trust the source of this workbook, click Yes.

Once I click Yes the file opens and looking at the XML file that directs me to I find the following:

<?xml version="1.0" encoding="UTF-8" standalone="true"?>
<recoveryLog xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
    <logFileName>error050360_01.xml</logFileName>
    <summary>Errors were detected in file 'C:\xxx\file.xlsb'</summary>
    <removedRecords summary="Following is a list of removed records:">
        <removedRecord>Removed Records: Sorting from /xl/worksheets/sheet11.bin part</removedRecord>
    </removedRecords>
</recoveryLog>
Run Code Online (Sandbox Code Playgroud)

On Sheet11 I have the following sorting code:

LastRow = ActiveSheet.Range("A1").Offset(ActiveSheet.Rows.Count - 1, 0).End(xlUp).Row
Range("A3").Select
ActiveWorkbook.Worksheets("AP_PV").Sort.SortFields.Clear
ActiveWorkbook.Worksheets("AP_PV").Sort.SortFields.Add key:=Range("A4:A" & LastRow) _
    , SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets("AP_PV").Sort
    .SetRange Range("A3:B" & LastRow)
    .Header = xlYes
    .MatchCase = False
    .Orientation = xlTopToBottom
    .SortMethod = xlPinYin
    .Apply
End With
Run Code Online (Sandbox Code Playgroud)

I tried adding a condition before Range("A3").Select to see if LastRow > 4 to exclude the sorting, but id didn't make any difference.

Any ideas on what is causing the corruption and how to avoid it?

小智 5

我会对此发表评论,只是提供链接,但我还没有 50 声望。

几年前的谷歌搜索发现了一个 SE 线程,其中包含大量可能的解决方案:Excel 错误:已删除记录:从 /xl/worksheets/sheet10.xml 部分排序

最有可能工作的是这个:

Sheets(yoursheetname).Sort.SortFields.Clear
Run Code Online (Sandbox Code Playgroud)

把它放在排序函数之后(或保存文件之前),似乎问题应该得到解决。

希望这有效。

当 SortFields.Add2 Key 使用普通范围(例如 Range("B2:B100") 时,不会发生此错误。但是,当使用变量设置 SortFields.Add2 的范围时,似乎总是会发生此错误关键。上面提供的解决方案有效 - 但仅在使用变量时才需要。由于使用宏记录器时(最后)不包含此行,因此我认为它属于错误。