Excel 名單含 600 位學生,照片檔置於同一資料夾,檔名為學號(如 12345.jpg)。需將照片批量插入對應學生列,逐一手動插入不現實。
filePath & Range("A" & i).Value & ".jpg"(假設學號在 A 欄)。Sub BatchInsertPhotos()
Dim ws As Worksheet, picPath As String, i As Long, lastRow As Long
Set ws = ActiveSheet
picPath = "C:\Photos\" ' 照片資料夾路徑,結尾加反斜線
lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
For i = 2 To lastRow ' 假設第 1 列為標題
Dim stuID As String
stuID = ws.Cells(i, "A").Value ' 學號欄
If stuID <> "" Then
Dim fullPath As String
fullPath = picPath & stuID & ".jpg"
If Dir(fullPath) <> "" Then
With ws.Pictures.Insert(fullPath)
.Top = ws.Cells(i, "B").Top ' 假設照片放 B 欄
.Left = ws.Cells(i, "B").Left
.ShapeRange.LockAspectRatio = msoTrue
.Width = 100 ' 依需求調整寬度
End With
End If
End If
Next i
End Sub
從「錄製巨集」起步,觀察語法 → 逐步替換為變數 → 加入迴圈與錯誤處理。VBA 學習貴在「敢於摸索、多動手實作」。