若員工照片檔名與姓名一致(如「張三.jpg」),且照片資料夾與活頁簿同目錄,即可用 VBA 批量插入照片至對應儲存格。
姓名.jpg(或 .gif、.png,程式碼中需對應修改)。


電腦教程
Sub AutoAddPic()
' 1. 先刪除工作表所有現有圖片
Dim Shp As Shape
For Each Shp In ActiveSheet.Shapes
If Shp.Type = msoPicture Then Shp.Delete
Next
' 2. 逐列處理有效資料區域
Dim MyPcName As String
Dim i As Long
Dim MyFile As Object
Set MyFile = CreateObject("Scripting.FileSystemObject")
For i = 1 To ActiveSheet.UsedRange.Rows.Count
' 判斷第1欄是否為「姓名」標題列(或直接判斷第2欄有值)
If ActiveSheet.Cells(i, 1).Value = "姓名" Then
MyPcName = ActiveSheet.Cells(i, 2).Value & ".jpg" ' 照片檔名
Dim FullPath As String
FullPath = ThisWorkbook.Path & "\員工照片\" & MyPcName
' 3. 選取目標儲存格(姓名下方2列,即 C 欄)
ActiveSheet.Cells(i + 2, 2).Select
' 4. 檢查檔案是否存在並插入
If MyFile.FileExists(FullPath) = False Then
MsgBox FullPath & " 圖片不存在"
Else
ActiveSheet.Pictures.Insert(FullPath).Select
' 可在此調整圖片大小:Selection.ShapeRange.LockAspectRatio = msoTrue: Selection.Width = 100
End If
End If
Next i
End Sub
AutoAddPic →「執行」。


| 程式碼片段 | 功能說明 |
|---|---|
ThisWorkbook.Path & "\員工照片\" | 取得活頁簿所在資料夾下的「員工照片」子資料夾完整路徑 |
ActiveSheet.Cells(i, 2).Value & ".jpg" | 組合照片檔名:姓名 + 副檔名 |
MyFile.FileExists(FullPath) | 使用 FileSystemObject 檢查檔案存在,避免插入失敗報錯 |
ActiveSheet.Cells(i + 2, 2).Select | 選取插入目標儲存格(姓名列下移 2 列,B 欄) |
ActiveSheet.Pictures.Insert(FullPath) | 在選取儲存格插入圖片 |