我添加名为“.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中任何东西,它通常是将没有必要和减慢你的代码。
我一直在PC和Mac上运行的系统上,并挣扎着找到插入PC和Mac上的照片的工作代码。 这为我工作,所以希望其他人可以使用它!
注:strPictureFilePath和strPictureFileName变量需要设置为有效PC和Mac的路径如
对于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返回涉及到左上角停放在小区范围内的对象的属性。 若要将一个新的形象,在一个特定的地方,我建议建立在“正确”的地方的图像和登记工作,顶部和左侧的属性假人的值到double变量。
插入分配给一个变量来很容易地改变它的名字你的照片。 Shape对象将具有相同的名称,图片对象。
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
祝好运!