尝试打印到PDF,卡在最后一步(使用Sendkeys自动保存为文件)msExcel 2003

时间:2012-01-23 18:43:48

标签: excel-vba vba excel

我尝试自动创建PDF文件(没有任何用户界面,只需点击excel文件中的按钮)。我似乎使用下面的代码得到了一切,但当它归结为将文件保存为自动生成的名称时,代码似乎停止用户并且它提示我输入要使用的文件名(而不是从代码中自动获取它) )。我有一种感觉,sendkeys对我不起作用。任何人都可以快速浏览一下吗?

感谢 macutan

Sub PrinttoPDFTest()

ActiveSheet.PageSetup.PrintArea = "$A$1:$F$17"
With ActiveSheet.PageSetup
    .PrintTitleRows = ""
    .PrintTitleColumns = ""
End With
ActiveSheet.PageSetup.PrintArea = "$A$1:$F$17"
With ActiveSheet.PageSetup
    .Orientation = xlLandscape
    .FitToPagesWide = 1
    .FitToPagesTall = 1
End With

ActiveWindow.SelectedSheets.PrintOut Copies:=1, ActivePrinter:="Adobe PDF on Ne04:", Collate:=True

newHour = Hour(Now())
newMinute = Minute(Now())
newSecond = Second(Now()) + 5
waitTime = TimeSerial(newHour, newMinute, newSecond)
Application.Wait waitTime

Filename = "C:\Temp\PDF\" & ActiveSheet.Range("DateSerial").Value & ".pdf"

SendKeys Filename & "{Enter}", False

End Sub

ActiveSheet.PageSetup.PrintArea = "$A$1:$F$17" With ActiveSheet.PageSetup .PrintTitleRows = "" .PrintTitleColumns = "" End With ActiveSheet.PageSetup.PrintArea = "$A$1:$F$17" With ActiveSheet.PageSetup .Orientation = xlLandscape .FitToPagesWide = 1 .FitToPagesTall = 1 End With ActiveWindow.SelectedSheets.PrintOut Copies:=1, ActivePrinter:="Adobe PDF on Ne04:", Collate:=True newHour = Hour(Now()) newMinute = Minute(Now()) newSecond = Second(Now()) + 5 waitTime = TimeSerial(newHour, newMinute, newSecond) Application.Wait waitTime Filename = "C:\Temp\PDF\" & ActiveSheet.Range("DateSerial").Value & ".pdf" SendKeys Filename & "{Enter}", False End Sub

1 个答案:

答案 0 :(得分:5)

使用.ExportAsFixedFormat而不是.PrintOut会更简单,只需堆叠您的请求(无需延迟代码):

Sub ExporttoPDF()

    Sheets("Sheet1").ExportAsFixedFormat xlTypePDF, "C:\Folder\Filename1.pdf"
    Sheets("Sheet2").ExportAsFixedFormat xlTypePDF, "C:\Folder\Filename2.pdf"

End Sub

只需替换目标和文件名,此代码应该可以正常工作。如果你想在工作表中使用一个值作为文件名的一部分,那么你可以像这样连接(&):

Sheets("Sheet1").ExportAsFixedFormat xlTypePDF, "C:\Folder\" & Range("P10").Value & ".pdf"

或者将文件名存储在变量中并按以下方式执行:

dim filename as string

filename = Range("P10").Value

Sheets("Sheet1").ExportAsFixedFormat xlTypePDF, filename

它一直在继续......