如何使用VBA宏循环打开pdf文件

时间:2019-04-25 09:38:17

标签: excel vba subscript

我在lbound和uboud上的错误超出范围。请帮忙。这是我的代码。 它在我制作的其他宏上的工作。 错误从ubound和lbound开始。当我运行它时,导致下标错误。我只是复制过去的代码。

Option Explicit
Public pdfpath, excelpath As String
Public pdfname, fname, issuename, excelname As String
Public wb As Workbook
Public ws, wspdf As Worksheet
Public STRinvoice, STRamnt, STRissue, STRcus As String
Public SAPinvoice, SAPamnt, SAPissue, SAPcus As String
Public i, ctr As Long
Public rfile() As Variant

Sub DO_ALL()

pdfpath = "C:\Users\" & Environ$("Username") & "\Desktop\Wiley Checker\PDF IN\"
excelpath = "C:\Users\" & Environ$("Username") & "\Desktop\Wiley Checker\EXCEL IN\"
pdfname = Dir(pdfpath & "*.pdf*")
ctr = 1


Set wb = ActiveWorkbook
Set ws = wb.Sheets("Checker")
Set wspdf = wb.Sheets("PDF")


Do Until pdfname = ""
    If InStr(pdfname, "pdf") > 0 Then
        ReDim Preserve rfile(1 To ctr)
        rfile(ctr) = pdfname
        ctr = ctr + 1
    End If
pdfname = Dir
Loop

For i = LBound(rfile) To UBound(rfile)

ActiveWorkbook.FollowHyperlink pdfpath & rfile(i)
'continous codes.....
Next i

Exit Sub

End Sub

我只想循环打开pdf文件。

1 个答案:

答案 0 :(得分:1)

很有可能未初始化Array rfile。请检查您是否有pdfpath文件,并且至少有一个文件通过了InStr(pdfname,“ pdf”)检查。

为了安全起见,请使用:

If ctr > 1 Then
    For i = LBound(rfile) To UBound(rfile)

    ActiveWorkbook.FollowHyperlink pdfpath & rfile(i)
    'continous codes.....
    Next i
End If