萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 辦公室軟體 >  >> Excel 教學 >> Excel 綜合

Excel 批量匯入員工照片:檔名對應姓名/工號,VBA 一鍵匯入並自動縮放定位

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

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

使用說明

  1. 照片檔名需包含可比對鍵值(姓名、工號、編號)。
  2. 調整程式碼中 `fPath`、`rng` 範圍、`Offset` 目標欄位。
  3. Alt+F11 開啟 VBE → 插入模組 → 貼上程式碼 → 執行。

無程式替代方案(Excel 365)

使用 IMAGE 函數(需 OneDrive/SharePoint 雲端路徑):=IMAGE("https://path/to/" & A2 & ".jpg"),公式直接顯示圖片,隨資料動態更新,零巨集、跨平台可用。

copyright © 萬盛學電腦網 all rights reserved