Applescript/Excel 将图表保存为图片

Applescript/Excel Saving Charts as Images

我正在尝试将名为 charts 的 sheet 中的第一个图表以 PNG 格式保存到桌面。我在 "save as picture" 行收到以下错误:

错误"Microsoft Excel got an error: Parameter error."数-50

tell application "Microsoft Excel"
    set theChart to first chart object of sheet "Charts"
    set filePath to "Macintosh HD:Users:User:Desktop:Chart.png" as text
    save as picture theChart picture type save as PNG file file name filePath
end tell

我也试过告诉图表本身并收到同样的错误:

tell theChart
    save as picture picture type save as PNG file file name filePath
end tell

根据字典和其他已知示例,语法似乎是正确的,但我们将不胜感激。

Microsoft Office 2016使用脚本时对安全性要求非常严格

  • 如果文件已经存在,则错误号-50。
  • 如果最近文件列表中没有该文件夹中的文件 Excel,然后是错误编号 -50.

解决方法,使用这个:

set myFolder to path to desktop folder
tell application "Microsoft Excel"
    alias myFolder --  first,  need this line to grant access to the folder before saving the PNG file , otherwise --> Parameter error.  number -50
    my deleteIfExists(myFolder, "Chart.png") -- second,  if the file already exists, then delete the file,  otherwise --> Parameter error.  number -50

    set theChart to first chart object of sheet "Charts"
    save as picture theChart picture type save as PNG file file name ((myFolder as string) & "Chart.png")
end tell

on deleteIfExists(f, tName) -- move the file to the trash
    tell application "Finder" to tell item tName of folder f to if exists then delete
end deleteIfExists