案例
案例來(lái)源:Excel和Access (微信公眾號(hào))點(diǎn)擊 - 查看原文

案例圖一
在指定單元格位置,批量插入多張圖片。
附件:點(diǎn)擊查看-百度云
提取密碼:i4n0
一、數(shù)據(jù)源代碼
復(fù)制代碼到Excel 表里,可以直接生案例數(shù)據(jù)。
Sub 數(shù)據(jù)源代碼()
'錄入數(shù)據(jù)
Cells(1, 1) = "代號(hào)"
Cells(1, 2) = "姓名"
Cells(1, 3) = "部門"
Cells(1, 4) = "照片"
Cells(2, 1) = "A12"
Cells(2, 2) = "何炅"
Cells(2, 3) = "技術(shù)部"
Cells(3, 1) = "A13"
Cells(3, 2) = "趙薇"
Cells(3, 3) = "開(kāi)發(fā)部"
Cells(4, 1) = "A14"
Cells(4, 2) = "黃渤"
Cells(4, 3) = "發(fā)展部"
Cells(5, 1) = "A15"
Cells(5, 2) = "胡歌"
Cells(5, 3) = "銷售部"
'調(diào)整格式
With Range("a1:d1")
.Font.Size = 16
.Font.Bold = True
.Interior.ColorIndex = 15 '設(shè)置背景顏色
.HorizontalAlignment = xlCenter
End With
With Range("a2:d5")
.RowHeight = 93 '行高93
.HorizontalAlignment = xlCenter
.VerticalAlignment = xlCenter
End With
Range("d:d").ColumnWidth = 13 '照片列寬13
Range("a1:d5").Borders.LineStyle = 1
ActiveWindow.DisplayGridlines = False
End Sub
- .RowHeight 設(shè)置行高
- .ColumnWidth 設(shè)置列寬
二、插入圖片
Sub 指定單元格位置插入圖片()
Dim strPic As String
Dim i, n As Integer
n = 1000 '預(yù)設(shè)查詢1000個(gè)位置
For i = 2 To Range("b" & n).End(xlUp).Row
strPic = ThisWorkbook.Path & "\2018-09-30 指定單元格位置批量插入圖片例圖\" & Range("b" & i) & ".jpg"
If Dir(strPic) <> "" Then
ActiveSheet.Shapes.AddPicture strPic, True, True, 157, 21 + (i - 2) * 93, 81, 92
End If
Next
End Sub
- .Shapes.AddPicture 插入對(duì)象,鏈接到文件,一起保存,左上角位置,頂端位置,寬度,高度
Dir函數(shù),用于判斷文件是否存在;
Shapes.AddPicture 插入圖片。
三、刪除圖片
Sub 刪除所有圖片()
Dim Shp As Shape
For Each Shp In ActiveSheet.Shapes
If Shp.Type = msoLinkedPicture Then Shp.Delete
Next
End Sub
1 首先定義Shp是Shape形狀類型;
2 然后定位,Shp在激活的表里,歸屬于Shapes其中一員;
3 循環(huán)判斷,如果Shp的類型是鏈接圖片類型,則刪除Shp文件;
4 Shap類型參考,可以使用參數(shù)名,也可使用參數(shù)值。Shap類型參考圖
