幾百張員工照片要放進 Excel 人事檔?檔名若包含姓名或工號(如 王小明_1001.jpg),VBA 巨集可批量讀取資料夾、比對工作表姓名/工號欄、自動插入照片並鎖定儲存格大小位置,秒殺手動插入。

Sub ImportPhotos()
Dim ws As Worksheet, fPath As String, fName As String
Dim rng As Cell, picPath As String, shp As Shape
Set ws = ActiveSheet
fPath = "C:\Photos\" ' 照片資料夾路徑,結尾需有 \
For Each rng In ws.Range("A2:A" & ws.Cells(ws.Rows.Count, "A").End(xlUp).Row) ' 假設 A 欄為姓名/工號
fName = Dir(fPath & rng.Value & "*.jpg") ' 支援模糊比對
If fName <> "" Then
picPath = fPath & fName
Set shp = ws.Pictures.Insert(picPath)
With shp
.ShapeStyle = msoShapeStylePreset1
.LockAspectRatio = msoTrue
.Width = rng.Offset(0, 1).Width ' 鎖定寬度為 B 欄寬
.Height = rng.Height
.Top = rng.Top
.Left = rng.Offset(0, 1).Left ' 放在 B 欄
.Placement = xlMoveAndSize ' 隨儲存格移動調整大小
End With
End If
Next rng
End Sub
使用 IMAGE 函數(需 OneDrive/SharePoint 雲端路徑):=IMAGE("https://path/to/" & A2 & ".jpg"),公式直接顯示圖片,隨資料動態更新,零巨集、跨平台可用。