2010-12-17 96 views
1

試圖通過「GetFullNamePDF()」的文件名屬性,但得到以下錯誤:「編譯錯誤:預期結束子」VBA錯誤:「編譯錯誤:預期結束子」

Sub PrintPDF() 

    Function GetFullNamePDF() As String 
     GetFullNameCSV = Replace(ThisWorkbook.FullName, ".xlsm", ".pdf") 
    End Function 

    ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _ 
     "GetFullNamePDF()", Quality:=xlQualityStandard, IncludeDocProperties _ 
     :=True, IgnorePrintAreas:=False, OpenAfterPublish:=False 

End Sub 

我知道沒有任何關於VBA,並從question I asked yesterday得到上述代碼,但當時無法測試。猜測錯誤與函數有關,因爲代碼沒有添加函數並且文件路徑/名稱被硬編碼。

代碼的想法是動態使用它自己的文件名來命名PDF的路徑和文件。如果您有任何問題,請點評 - 謝謝!

回答

3

不能嵌套過程中的功能。你需要將它移動到上面:

Function GetFullNamePDF() As String 
    GetFullNameCSV = Replace(ThisWorkbook.FullName, ".xlsm", ".pdf") 
    'This should be 
    GetFullNamePDF = Replace(ThisWorkbook.FullName, ".xlsm", ".pdf") 
End Function 

Sub PrintPDF() 

    'Remove the quotes from GetFullNamePDF 
    ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _ 
     GetFullNamePDF(), Quality:=xlQualityStandard, IncludeDocProperties _ 
     :=True, IgnorePrintAreas:=False, OpenAfterPublish:=False 

End Sub 
+0

感謝您花時間閱讀代碼並確保一切正確;明智的我的代碼說我的代碼更好,但從未使用Excel的VBA。 – blunders 2010-12-17 15:47:39

+0

工程,只是測試它,謝謝! – blunders 2010-12-17 15:53:43

1

在子內聲明函數是非法的。 它應該是這樣的:

Function GetFullNamePDF() As String 
    GetFullNamePDF = Replace(ThisWorkbook.FullName, ".xlsm", ".pdf") 
End Function 


Sub PrintPDF() 
    ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _ 
     "GetFullNamePDF()", Quality:=xlQualityStandard, IncludeDocProperties _ 
     :=True, IgnorePrintAreas:=False, OpenAfterPublish:=False 
End Sub 
1

像這樣:

Function GetFullNamePDF() As String 
    GetFullNamePDF = Replace(ThisWorkbook.FullName, ".xlsm", ".pdf") 
End Function 

Sub PrintPDF() 
    Dim sFileName As Variable 

    sFileName=GetFullNamePDF() 

    ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _ 
     sFilename, Quality:=xlQualityStandard, IncludeDocProperties _ 
     :=True, IgnorePrintAreas:=False, OpenAfterPublish:=False 

End Sub 
+0

@Remou:在代碼中沒有提及「sFilename」,不要認爲這會起作用。 – blunders 2010-12-17 16:01:06

+0

@Blunder你忘了我寫了這個函數嗎?我非常非常熟悉VBA(檢查VBA標籤上的用戶)。將變量設置爲函數的結果並不罕見,這使得調試變得更加容易。在你重寫函數時有一個錯誤,我會糾正它。 – Fionnuala 2010-12-17 16:10:05

+0

@Remou:你是對的,它會工作 - 將一個變量設置爲函數結果的原因是什麼? – blunders 2010-12-17 16:16:54