Excel VBA addPicture by path to image

浪子不回头ぞ 提交于 2020-06-17 08:08:01

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!