问题
I've written an VBA Macro on windows. This Macro adds pictures into my excel sheet based on the value of a cell e.g. 'image.png'. These images are located in the same directory as my Excel workbook. VBA will get the path to the workbook and use it to find the image specified in the cell. This works on windows, however it does not work on mac. The macro returns an error (1004) saying it can't find the specified file.
Sub InsertImage()
Dim useless As Double
Dim clTop As Double
For Each c In ActiveSheet.Range("C3:C200").Cells
If c.Value = "" Then
useless = 1
Else
Set cl = Range(c, c.Offset(0, 1))
clTop = cl.Top
ActiveSheet.Shapes.AddPicture _
Application.ActiveWorkbook.Path & "\" & c.Value, _
True, True, 500, clTop, 140, 140
End If
Next
End Sub
UPDATE:
Did some more testing: When I first manually add all the pictures that I want to add, then immediatly delete them all, then run exactly the same Macro, all the pictures are imported perfectly fine. Could this be a bug in Excel for Mac?
回答1:
Leaving an answer here in case anyone still finds this page when banging their heads against a wall trying to insert multiple pictures into Excel for Mac, using VBA (like me). I found the GrantAccessToMultipleFiles help on this site here finally fixed it for me: https://warwick.ac.uk/fac/sci/systemsbiology/staff/dyer/software/excelvbafileopen/
回答2:
Macs don't use the same path separators as Windows (or even as each other). Change the code to this:
ActiveSheet.Shapes.AddPicture _
Application.ActiveWorkbook.Path & Application.PathSeparator & c.Value, _
msoFalse, msoTrue, 500, clTop, 140, 140
来源:https://stackoverflow.com/questions/39895106/excel-vba-addpicture-by-path-to-image