问题描述
我尝试了很多方法来修复此错误。谁能看出为什么这段代码说找不到文件?
Sub PdfPwd()
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Dim fTemp As String 'Defining Variables
Dim oPdf As String
Dim Pwd As String
fTemp = "C:\Users\JSmith.ODINSU\Documents\" & "Temp.Pdf"
oPdf = "C:\w2s\" & Sheets("w2 form").Range("q4").Value & ".pdf" 'Set Path and Name for Protected Output PDF here.
Pwd = Sheets("w2 form").Range("r4").Value 'Set appropriate Password here.
With ActiveSheet 'Making a Temporary Unprotected Pdf file.
.ExportAsFixedFormat Type:=xlTypePDF,_
Filename:=fTemp,_
Quality:=xlQualityStandard
End With
' fTemp = """" & fTemp & """" 'Putting extra "" around for command Parameter.
'Debug.Print fTemp
' oPdf = """" & oPdf & """"
'
' Pwd = """" & Pwd & """"
'Making Command String for making protected PDFs Using PDFtk tool.
cmdstr = "pdftk " & fTemp _
& " Output " & oPdf _
& " User_pw " & Pwd _
& " Allow AllFeatures"
Debug.Print cmdstr
Shell cmdstr,vbHide 'Executing PDFtk Command.
Application.Wait DateAdd("s",2,Now) 'Allowing 2 secs for command to execute.
Kill Replace(fTemp,"""","") 'Deleting temporary files.
Application.ScreenUpdating = True
Application.DisplayAlerts = True
MsgBox "Finished",vbInformation
End Sub
这是我得到的文件路径。
pdftk C:\Users\JSmith.ODINSU\Documents\Temp.Pdf 输出 C:\w2s\10CARRACCorrectedW2.pdf User_pw 123456 允许所有功能
当我将该行复制并粘贴到 cmd 中并运行它时,一切正常。
解决方法
我终于想通了。这是有效的代码。我排除了 end sub,因为我在代码中添加了一个电子邮件组件。
Dim rng As Range
Set rng = Sheets("w2 form").Range("at6:at9")
For Each cell In rng
fTemp = "C:\" & "Temp.Pdf"
oPdf = "C:\w2s\" & Sheets("w2 form").Range("q4").Value & ".pdf" 'Set Path and Name for Protected Output PDF here.
Pwd = Sheets("w2 form").Range("r4").Value 'Set appropriate Password here.
With ActiveSheet 'Making a Temporary Unprotected Pdf file.
.ExportAsFixedFormat Type:=xlTypePDF,_
Filename:=fTemp,_
Quality:=xlQualityStandard
End With
fTemp = """" & fTemp & """" 'Putting extra "" around for command Parameter.
Debug.Print fTemp
oPdf = """" & oPdf & """"
Pwd = """" & Pwd & """"
'Making Command String for making protected PDFs Using PDFtk tool.
cmdstr = "pdftk " & fTemp _
& " Output " & oPdf _
& " User_pw " & Pwd _
& " Allow AllFeatures"
Debug.Print cmdstr
Shell cmdstr,vbHide 'Executing PDFtk Command.
Application.Wait DateAdd("s",2,Now) 'Allowing 2 secs for command to execute.
Kill Replace(fTemp,"""","") 'Deleting temporary files.