我如何解决这个错误“微软Excel正在等待另一个应用程序完成一个ole操作”?

ckx4rj1h  于 2023-11-20  发布在  其他
关注(0)|答案(1)|浏览(455)

我试图转换pdf文件到excel文件。和转换器是完美的工作,但当它得到大pdf与像300页“微软excel正在等待另一个应用程序完成ole行动”错误出现。
代码如下:

Option Explicit

Sub PDF_To_Excel()

Dim setting_sh As Worksheet
Set setting_sh = ThisWorkbook.Sheets("Setting")

Dim pdf_path As String
Dim excel_path As String

pdf_path = setting_sh.Range("E11").Value
excel_path = setting_sh.Range("E12").Value

Dim fso As New FileSystemObject
Dim fo As Folder
Dim f As File

Set fo = fso.GetFolder(pdf_path)

Dim wa As Object
Dim doc As Object
Dim wr As Object

Set wa = CreateObject("word.application")

wa.Visible = True

Dim nwb As Workbook
Dim nsh As Worksheet

For Each f In fo.Files
Set doc = wa.documents.Open(f.Path, False, Format:="PDF Files")
Set wr = doc.Paragraphs(1).Range
wr.WholeStory

Set nwb = Workbooks.Add
Set nsh = nwb.Sheets(1)
wr.Copy

nsh.Paste
nwb.SaveAs (excel_path & "\" & Replace(f.Name, ".pdf", ".xlsx"))

doc.Close False
nwb.Close False
Next

wa.Quit

MsgBox "Done"

End Sub

字符串
我试着做一些设置,但没有帮助。Application.wait和Application.DisplayAlerts = False也没有帮助。
有什么我能做的吗?还是这些文件太大了?

kgsdhlau

kgsdhlau1#

我还没有测试过这个,但这里有一些想法......
处理大型PDF文件并将其转换为Excel可能会占用大量资源,并且您似乎遇到了当前方法的问题。以下是一些可能会有所帮助的建议:

批量处理:与其一次处理所有300页,不如考虑一次处理更小的块或页面。您可以修改循环以在每次迭代中处理特定范围的页面。

For Each f In fo.Files
    Set doc = wa.documents.Open(f.Path, False, Format:="PDF Files")

    Dim startPage As Integer
    Dim endPage As Integer
    Dim pageStep As Integer
    startPage = 1
    pageStep = 50  ' Adjust this based on your needs
'doc.ComputeStatistics(2) returns the total number of pages in the PDF document 
    Do While startPage <= doc.ComputeStatistics(2)
        endPage = startPage + pageStep - 1
        If endPage > doc.ComputeStatistics(2) Then
            endPage = doc.ComputeStatistics(2)
        End If

        Set wr = doc.Range(doc.GoTo(What:=1, Which:=1, Count:=startPage), doc.GoTo(What:=1, Which:=1, Count:=endPage))
        Set nwb = Workbooks.Add
        Set nsh = nwb.Sheets(1)
        wr.Copy
        nsh.Paste

        nwb.SaveAs (excel_path & "\" & Replace(f.Name, ".pdf", "_Pages_" & startPage & "-" & endPage & ".xlsx"))

        nwb.Close False
        startPage = endPage + 1
    Loop

    doc.Close False
Next

字符串

内存管理:大型PDF文件可能会占用大量内存。请确保释放对象并正确管理内存。处理完对象后,请将对象设置为Nothing。

Set doc = Nothing
Set wr = Nothing
Set nwb = Nothing
Set nsh = Nothing

错误处理:执行正确的错误处理以确定问题的确切位置。添加错误恢复下一个并检查关键语句后的错误。

On Error Resume Next
' Your code here
If Err.Number <> 0 Then
    MsgBox "Error: " & Err.Description
End If
On Error GoTo 0  ' Reset error handling

相关问题