PDA

View Full Version : [SOLVED:] Mac VBA open an image



nicolascrab
02-22-2023, 03:20 PM
Hi,

I'm a beginner in VBA, I dabbled with VBA on Windows before but only basic copy/paste/save, moving data around the sheet stuff, so bear with me please:)

I'd like to open a .png image with Preview (my default image viewer) using VBA.
Let's say for simplicity's sake that the ImgPath = "/Users/nicolascrab/Documents/IMG.png"

I haven't found any straightforward solutions on Google as everyone is talking about how to open another workbook or a file. Can anyone help me or point me to the right direction on how to solve this? Thanks!

nicolascrab
02-25-2023, 02:20 PM
Alright, so after a bit of trial and error I found a solution and I thought I'd post it here in case anyone finds this thread later on.

1) Set up an AppleScript file in your "/Users/USERNAME/Library/Application Scripts/com.microsoft.Excel" folder and name it "openImgScript.scpt"

To do this, you need to open the Script Editor and create a script with the following code:


on openFileWithPath(myParamString)
set fullPath to myParamString
do shell script "open " & quoted form of fullPath
end openFileWithPath

This file opens an image if you pass the file's path to it.
Save it to /Users/USERNAME/Library/Application Scripts/com.microsoft.Excel/openImgScript.scpt
Note that "Library" is a hidden folder so it's a bit tricky to access it.

2) Once you placed the script to the proper location, now we gotta call this script from VBA using the following VBA code:


Sub openImgMac()

'Declare path and mac script variables
Dim myPath As String
Dim myScriptResult As String

'REPLACE WITH YOUR PATH
myPath = "/Users/username/Documents/image.png"

'open the img
myScriptResult = AppleScriptTask("openImgScript.scpt", "OpenFileWithPath", myPath)
End Sub


3) This VBA calls the script and passes your img path as a parameter.:hi:

Aussiebear
02-25-2023, 04:57 PM
Thank you for posting the solution