如何使用VBA将图片插入指定单元格位置的Excel中

我用下面的代码将“.jpg”文件添加到我的Excel工作表中:

'Add picture to excel xlApp.Cells(i, 20).Select xlApp.ActiveSheet.Pictures.Insert(picPath).Select 'Calgulate new picture size With xlApp.Selection.ShapeRange .LockAspectRatio = msoTrue .Width = 75 .Height = 100 End With 'Resize and make printable With xlApp.Selection .Placement = 1 'xlMoveAndSize '.Placement = 2 'xlMove '.Placement = 3 'xlFreeFloating .PrintObject = True End With 

我不知道我在做什么错,但它没有插入到正确的单元格,所以我应该怎么做,把这张图片放入Excel中的指定单元格?

尝试这个:

 With xlApp.ActiveSheet.Pictures.Insert(PicPath) With .ShapeRange .LockAspectRatio = msoTrue .Width = 75 .Height = 100 End With .Left = xlApp.ActiveSheet.Cells(i, 20).Left .Top = xlApp.ActiveSheet.Cells(i, 20).Top .Placement = 1 .PrintObject = True End With 

最好不要在Excel中select任何东西,这通常是不必要的,并会减慢你的代码。

我一直在研究在PC和Mac上运行的系统,并且正在努力寻找在PC和Mac上插入图片的代码。 这对我有用,所以希望别人可以利用它!

注意:strPictureFilePath和strPictureFileNamevariables需要设置为有效的PC和Macpath

对于PC:strPictureFilePath =“E:\ Dropbox \”和strPictureFileName =“TestImage.jpg”和Mac:strPictureFilePath =“Macintosh HD:Dropbox:”和strPictureFileName =“TestImage.jpg”

代码如下:

  On Error GoTo ErrorOccured shtRecipeBrowser.Cells(intDestinationRecipeRowCount, 1).Select ActiveSheet.Pictures.Insert(Trim(strPictureFilePath & strPictureFileName)).Select Selection.ShapeRange.Left = shtRecipeBrowser.Cells(intDestinationRecipeRowCount, 1).Left Selection.ShapeRange.Top = shtRecipeBrowser.Cells(intDestinationRecipeRowCount, 1).Top + 10 Selection.ShapeRange.LockAspectRatio = msoTrue Selection.ShapeRange.Height = 130 

如果仅仅是插入和调整图片大小,请尝试下面的代码。

对于您提出的具体问题,TopLeftCell属性返回与左上angular停放的单元格相关的范围对象。 要在特定位置放置新图像,我build议在“正确”位置创build一个图像,并将其虚拟的顶部和左侧属性值注册到双variables中。

插入你的图片分配给一个variables,轻松地改变它的名字。 形状对象将具有与图片对象相同的名称。

 Sub Insert_Pic_From_File(PicPath as string, wsDestination as worksheet) Dim Pic As Picture, Shp as Shape Set Pic = wsDestination.Pictures.Insert(FilePath) Pic.Name = "myPicture" 'Strongly recommend using a FileSystemObject.FileExists method to check if the path is good before executing the previous command Set Shp = wsDestination.Shapes("myPicture") With Shp .Height = 100 .Width = 75 .LockAspectRatio = msoTrue 'Put this later so that changing height doesn't change width and vice-versa) .Placement = 1 .Top = 100 .Left = 100 End with End Sub 

祝你好运!