简体   繁体   中英

Macro to export Excel Doc as PDF for all Users

I need to create a macro that will save an excel document as a PDF file to any user's desktop (ie multiple people will be using this document/macro).

Here is VBA code I have so far:

Sub CreatePDF()
'
' CreatePDF Macro
'

'
    ChDir "C:\Users\Public\Desktop"
    ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
        "C:\Users\Public\Desktop\QuickView Update Dec_2017.pdf", Quality:= _
        xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, _
        OpenAfterPublish:=True
End Sub

I think the issue is with the directory it's saving to (in the instances where this code says "Public" in the file path, I had changed that from my username which was initially populated).

Does anyone know a way to specify a generic path to save this document as a PDF to any users' desktop?

Use .specialfolders("Desktop") to save to the desktop. Set to a string variable and add the path separator

Example

Option Explicit
Sub CreatePDF()
    Dim FilePath As String
            
    FilePath = CreateObject("WScript.Shell").specialfolders("Desktop")
    
    Debug.Print FilePath
    
    ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _
                    FileName:=FilePath & "\" & "QuickView Update Dec_2017.pdf", _
                    Quality:=xlQualityStandard, _
                    IncludeDocProperties:=True, _
                    IgnorePrintAreas:=False, _
                    OpenAfterPublish:=True
                    
End Sub

The following special folders are available:

  • AllUsersDesktop
  • AllUsersStartMenu
  • AllUsersPrograms
  • AllUsersStartup
  • Desktop
  • Favorites
  • Fonts
  • MyDocuments
  • NetHood
  • PrintHood
  • Programs
  • Recent
  • SendTo
  • StartMenu
  • Startup
  • Templates

The SpecialFolders property returns an empty string if the requested folder (strFolderName) is not available. For example, Windows 95 does not have an AllUsersDesktop folder and returns an empty string if strFolderNameis AllUsersDesktop.


Here is another example https://stackoverflow.com/a/31694603/4539709

You can use environment variables. %USERPROFILE%\\Desktop should work in this instance.

Here's a list of environment variables. https://en.wikipedia.org/wiki/Environment_variable#Default_Values

Accessing environment variables with VBA: Environ Function code samples for VBA

In VBA you could translate it to Environ("USERPROFILE") & "\\Desktop" This is untested as I'm not using Windows.

I have not tested this but based on what you gave try :

Dim url As String
url = Application.DefaultFilePath & "\" & ActiveWorkbook.Name & ".xls"

in your export part of your code replace filename:= blah blah to Filename:=url

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM