您不能将图片“放入”一个单元格,只能“覆盖”它。所有图片“浮动”在工作表上。您可以通过将图片的 Top 和 Left 属性设置为单元格的 Top 和 Left 来将图片放置在单元格上。
Sub AddPicOverCell(path As String, filename As String, rngRangeForPicture As Range)
With Application
Dim StartingScreenUpdateing As Boolean
Dim StartingEnabledEvent As Boolean
Dim StartingCalculations As XlCalculation
StartingScreenUpdateing = .ScreenUpdating
StartingEnabledEvent = .EnableEvents
StartingCalculations = .Calculation
.ScreenUpdating = False
.EnableEvents = False
.Calculation = xlCalculationManual
End With
Dim Top As Single, Left As Single, Height As Single, Width As Single
Dim file As String
Dim ws As Worksheet
file = path + "/" + filename + ".png"
Top = rngRangeForPicture.Top
Left = rngRangeForPicture.Left
Height = rngRangeForPicture.Height
Width = rngRangeForPicture.Width
Set ws = rngRangeForPicture.Worksheet
ws.Shapes.AddPicture file, msoCTrue, msoTrue, Left, Top, Width, Height
With Application
.ScreenUpdating = StartingScreenUpdateing
.EnableEvents = StartingEnabledEvent
.Calculation = StartingCalculations
End With
End Sub
然后你会这样称呼它:
AddPicOverCell "C:\", "Pic", ActiveSheet.Range("A1")
注意:这会将图像定位和调整大小,使其在工作表上的大小和位置与您在调用 sub 时指定的单元格相同。这会将图片插入到您想要图片的单元格或范围内。这也可以是一个单元格范围,B5:G25
或者在我的示例中是单个单元格Range("A1")
,图片将覆盖该范围内的所有单元格。