通过VBA更有效地打开外部工作表,导出为PDF并关闭它

时间:2015-07-11 10:57:17

标签: excel vba excel-vba pdf-generation

写了这个基于给定JobNumber的宏,找到合同(excel工作簿)的路径,打开它,将Sheet1导出为PDF,然后关闭它。 到目前为止测试它并且工作正常..任何人都可以指出更有效的方法来做这个宏正在做的事情吗?也许无需打开外部工作簿?

Public Sub saveMePDF()
Dim JobCat As String, JobNumber As String, JobNumberName As String, MainPath As String

JobCat = Sheet1.Range("V2").Text
JobNumber = Sheet1.Range("U2").Text
JobNumberName = Dir("C:\test\" & JobCat & "\" & JobNumber & "*", vbDirectory)
MainPath = "C:\test\" & JobCat & "\" & JobNumberName

'set to the current active workbook (the source book)
Set wbThis = ActiveWorkbook
Set wsThis = ActiveSheet

'open a workbook that has same name as the sheet name
Set wbTarget = Workbooks.Open(MainPath & "\Contracts\contract.xlsx")
Set wsTarget = wbTarget.Worksheets("Sheet1")

'activate the target worksheet
wbTarget.Activate

'export current active worksheet to pathed PDF
If JobNumber <> "" Then
    ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:=MainPath & "\Scheduling\EstimateTest3.pdf" _
, Quality:=xlQualityMedium, IncludeDocProperties:=False, _
IgnorePrintAreas:=False, OpenAfterPublish:=False

'close the workbook
wbTarget.Close

'activate the source book again
wbThis.Activate

'clear memory
Set wbTarget = Nothing
Set wbThis = Nothing

End If
End Sub

1 个答案:

答案 0 :(得分:1)

为表现我有两个想法: 1.关闭screenupdating: 在代码的开头:

Application.screenupdating = false

在结束之前结束:

Application.screenupdating = true
  1. 不要激活已打开的工作簿,只需使用指定的名称,如:
  2. 而不是activeworkbook使用您指定的工作簿名称,然后只删除激活部分。

    根据我的经验,上面两个会增加很多速度。 如果您试一试,请评论它是如何工作的。