简体   繁体   中英

Excel VBA, sorting, saving, closing, then opening

I have two Excel files, file1.xlsm and file2.xlsm; I have a data table in one, and soemthing else in the other. In the second file I also have a button which opens the first file.

In the first file I have a button which sorts all data using column A as the key and a second button to save and exit.

My code for sorting:

Private Sub CommandButton2_Click()
    Dim lRow As Long
    lRow = Cells(Rows.Count, 1).End(xlUp).Row
    With ActiveSheet.Sort
       .SortFields.Add Key:=Range("A3"), Order:=xlAscending
       .SetRange Range("A3:AF" & lRow)
       .Header = xlNo
       .Apply
    End With
End Sub

The problem is that after I sort, save and exit I cannot re-open the same workbook through VBA (the button does nothing); I can click on the file, then it opens but gives me an error that there were problems, yet Excel can recover. The error in error log:

Errors were detected in file 'C:\\file1.xlsm'
Removed Records: Sorting from
/xl/worksheets/sheet1.xml part

The button to save is just closing the workbook with SaveChanges:=True .

Why is this happening and how can it be rectified?

This Error

Errors were detected in file

means that your file is corrupt.

In many cases converting the file into the binary .xlsb format repairs the file. After that you can save at again in XML format .xlsm .

Nevertheless, I often had issues with the XML format and file corruption. So for big data I recommend to use the binary format (it's a bit more efficient and produces smaller files too).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM