简体   繁体   English

Excel VBA,排序,保存,关闭然后打开

[英]Excel VBA, sorting, saving, closing, then opening

I have two Excel files, file1.xlsm and file2.xlsm; 我有两个Excel文件,分别为file1.xlsm和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. 在第一个文件中,我有一个按钮,它使用A列作为键对所有数据进行排序,还有一个按钮,用于保存和退出。

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); 问题是排序,保存并退出后,我无法通过VBA重新打开同一工作簿(该按钮不执行任何操作); I can click on the file, then it opens but gives me an error that there were problems, yet Excel can recover. 我可以单击该文件,然后将其打开,但出现一个错误,提示我有问题,但是Excel可以恢复。 The error in error log: 错误日志中的错误:

Errors were detected in file 'C:\\file1.xlsm' 在文件'C:\\ file1.xlsm'中检测到错误
Removed Records: Sorting from 删除的记录:从排序
/xl/worksheets/sheet1.xml part /xl/worksheets/sheet1.xml部分

The button to save is just closing the workbook with SaveChanges:=True . 保存按钮只是使用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. 在许多情况下,将文件转换为二进制.xlsb格式可以修复文件。 After that you can save at again in XML format .xlsm . 之后,您可以再次以XML格式.xlsm保存。

Nevertheless, I often had issues with the XML format and file corruption. 但是,我经常遇到XML格式和文件损坏的问题。 So for big data I recommend to use the binary format (it's a bit more efficient and produces smaller files too). 因此,对于大数据,我建议使用二进制格式(效率更高,并且产生的文件也更小)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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