Excel加载项将文件名更改为加载项的名称,尽管它不应该

时间:2015-04-16 06:26:11

标签: excel vba excel-vba

我需要您关于我使用VBA创建的加载项的帮助,然后我保存为加载项,以便能够在所有Excel工作簿上使用并将其发送给我的朋友。

加载项只是将活动工作表中的打印区域保存为具有相同工作簿名称的PDF文件,它将PDF保存到桌面并作为宏工作正常。

但是当我以PDF格式保存并使用它时,它会使用与加载项相同的名称保存PDF文件,而不是工作簿的名称。

有什么建议吗?

VBA代码是:

Sub Save_as_pdf()
Dim FSO As Object
Dim s(1) As String
Dim sNewFilePath As String

    Set FSO = CreateObject("Scripting.FileSystemObject")

    s(0) = "C:\Users\" & Environ("UserName") & "\Desktop\" & ThisWorkbook.Name

    If FSO.FileExists(ThisWorkbook.FullName) Then
        '//Change Excel Extension to PDF extension in FilePath
        s(1) = FSO.GetExtensionName(s(0))

        If s(1) <> "" Then
            s(1) = "." & s(1)
            sNewFilePath = Replace(s(0), s(1), ".pdf")

            '//Export to PDF with new File Path
            ActiveSheet.ExportAsFixedFormat _
                Type:=xlTypePDF, _
                Filename:=sNewFilePath, _
                Quality:=xlQualityStandard, IncludeDocProperties:=True, _
                IgnorePrintAreas:=False, OpenAfterPublish:=True
        End If
    Else
        '//Error: file path not found
        MsgBox "Error: this workbook may be unsaved.  Please save and try again."
    End If

    Set FSO = Nothing

End Sub

1 个答案:

答案 0 :(得分:2)

详细说明Matteo NNZ上面的评论:

ThisWorkbook指的是当前正在执行代码的工作簿(在本例中为加载项)

ActiveWorkbook是指在同一Excel实例中当前处于活动状态的工作簿。