问与答102:如何按顺序将图片插入到工作表单元格中?
excelperfect
Q:我想将一些图片按顺序插入到工作表单元格中,例如从工作表当前单元格开始,向左每行插入3张图片,然后转到下一行再插入3张图片。如下图1所示,当前单元格为B2,当我选择了想要插入的图片后,从该单元格开始,第2行的3列单元格分别插入3张图片,然后转到下一行自左至右再插入3张图片,依此类推,直至所有图片都插入到工作表中。

图1
A:可以使用一段VBA代码实现。
Sub InsertPictures()
Dim PicList() As Variant
Dim PicFormat As String
Dim rngAs Range
Dim sShape As Shape
Dim xColIndex As Long
Dim xRowIndex As Long
Dim xStartColIndex As Long
Dim lLoop As Long
On Error Resume Next
'选择并获取图片
PicList =Application.GetOpenFilename(PicFormat, MultiSelect:=True)
'获取当前单元格所在的位置
xColIndex= Application.ActiveCell.Column
xRowIndex= Application.ActiveCell.Row
xStartColIndex = xColIndex
If IsArray(PicList) Then
'遍历图片列表并在工作表中插入图片
For lLoop = LBound(PicList) To UBound(PicList)
'获取并赋值单元格变量
Set rng = Cells(xRowIndex, xColIndex)
'插入图片
Set sShape = ActiveSheet.Shapes.AddPicture(PicList(lLoop), msoFalse,msoCTrue, rng.Left, rng.Top, rng.Width, rng.Height)
'控制图片插入位置
xColIndex = xColIndex + 1
If xColIndex = xStartColIndex + 3 Then
xRowIndex = xRowIndex + 1
xColIndex = xColIndex - 3
End If
Next lLoop
End If
End Sub
当然,你可以修改上述程序代码中的
If xColIndex = xStartColIndex + 3 Then
xRowIndex = xRowIndex + 1
xColIndex= xColIndex - 3
End If
用来控制在工作表中显示图片的列数。
