【问题标题】:Loop over spreadsheet rows to convert pdf to text using filenames in spreadsheet循环电子表格行以使用电子表格中的文件名将 pdf 转换为文本
【发布时间】:2018-09-03 00:25:06
【问题描述】:

我已经修改了下面的代码循环,以便它可以将多个 PDF 转换为文本文件。 PDF 文件名位于电子表格 A 列中,文本文件文件名位于电子表格 C 列中。但是,循环代码似乎不正确,因为我只能获取要转换的第一个文件并且它随机卡住。不知道有没有好心人能给点建议?谢谢!

Sub ConvertPDF()

Dim sfile As String, dfile As String
Dim AcroXApp As Acrobat.acroApp, AcroXAVDoc As Acrobat.AcroAVDoc
Dim AcroXPDDoc As Acrobat.AcroPDDoc, jsObj As Object, Row As Long

Row = 2

sfile = Sheet1.Range("A" & Row).Value
dfile = Sheet1.Range("C" & Row).Value

Do While ws("Sheet1").Range("A" & "row") <> ""
Set AcroXApp = CreateObject("AcroExch.App")
Set AcroXAVDoc = CreateObject("AcroExch.AVDoc")
AcroXAVDoc.Open sfile, "Acrobat"
Set AcroXPDDoc = AcroXAVDoc.GetPDDoc
Set jsObj = AcroXPDDoc.GetJSObject
jsObj.SaveAs dfile, "com.adobe.acrobat.plain-text"

AcroXAVDoc.Close False
AcroXApp.Hide
AcroXApp.Exit
Loop
Row = Row + 1

End Sub

【问题讨论】:

    标签: vba excel loops pdf


    【解决方案1】:

    Row = Row + 1 赋值应该在 Loop 语句之前,而不是在它之后。否则,Row 永远不会改变,给你你提到的行为。

    同样,sfile =...dfile = ... 应该在 Do 之后,而不是在它之前。您需要 DoLoop 之间的所有每个文件的代码。

    这是修改后的版本:

    Option Explicit   ' At the top of the file - always use it
    
    Sub ConvertPDF()
    
        Dim sfile As String, dfile As String
        Dim AcroXApp As Acrobat.acroApp, AcroXAVDoc As Acrobat.AcroAVDoc
        Dim AcroXPDDoc As Acrobat.AcroPDDoc, jsObj As Object, row As Long
    
        Dim row As Long       ' *** Added - required by Option Explicit
    
        row = 2
    
        Do While ws("Sheet1").Range("A" & CStr(row)) <> ""     ' *** Moved up; use CStr
    
            ' *** Now you are in the body of the loop, so do everything that relates to this row.
    
            sfile = Sheet1.Range("A" & CStr(row)).Value
            dfile = Sheet1.Range("C" & CStr(row)).Value
    
            Set AcroXApp = CreateObject("AcroExch.App")
            Set AcroXAVDoc = CreateObject("AcroExch.AVDoc")
            AcroXAVDoc.Open sfile, "Acrobat"
            Set AcroXPDDoc = AcroXAVDoc.GetPDDoc
            Set jsObj = AcroXPDDoc.GetJSObject
            jsObj.SaveAs dfile, "com.adobe.acrobat.plain-text"
    
            AcroXAVDoc.Close False
            AcroXApp.Hide
            AcroXApp.Exit
    
            ' *** End of the code for this row
    
            row = row + 1    ' *** Go on to the next row - moved before the Loop
        Loop
    End Sub
    

    CStr(foo) 明确地将foo 转换为字符串。为了清楚起见,我在上面添加了它。

    如果您愿意,您可以使用Cells 而不是Range 来进一步加快您的代码速度。

    【讨论】:

    • @chanhongchon 很高兴听到这个消息!并感谢您帮助将我推到 10k 声誉! :D :D
    猜你喜欢
    • 1970-01-01
    • 2013-08-20
    • 1970-01-01
    • 2021-09-18
    • 2013-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多