萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 辦公室軟體 >  >> PowerPoint 教學 >> PPT 基礎知識

PPT 批量匯入百張圖片:VBA 巨集一鍵自動化

場景:100 張照片各佔一頁,手動插入太瘋狂

利用 VBA 巨集,依檔名序號自動將圖片設為對應投影片背景,秒完成百頁相簿/簡報。

前置準備

  • 圖片命名規則:`C:\Pictures\1.jpg`、`2.jpg` ... `100.jpg`(連續數字、同副檔名、同資料夾)。
  • 建立與圖片數量相同的空白投影片:連續按 Ctrl+M 100 次(或巨集建立)。

VBA 程式碼

  1. Alt+F11 開啟 VBE →「插入」→「模組」。
  2. 貼上以下程式碼:
Sub InsertPic()
    Dim i As Integer
    For i = 1 To ActivePresentation.Slides.Count
        ActivePresentation.Slides(i).Select
        With ActiveWindow.Selection.SlideRange
            .FollowMasterBackground = msoFalse
            .Background.Fill.UserPicture "C:\Pictures\" & i & ".jpg"
        End With
    Next
End Sub
  1. 關閉 VBE,Alt+F8 開啟巨集對話框 → 選 `InsertPic` →「執行」。

程式碼解析

  • `Slides(i)`:第 i 張投影片(索引從 1 開始)。
  • `FollowMasterBackground = msoFalse`:解除母版背景繼承,允許單頁設定背景。
  • `Background.Fill.UserPicture`:將指定圖片設為背景填滿(自動裁切置中)。
  • 迴圈遍歷所有投影片,一一對應圖片序號。

進階擴充版本

Sub InsertPicAdvanced()
    Dim i As Long, picPath As String, ext As String
    ext = ".jpg"  ' 可改 .png .bmp
    picPath = "C:\Pictures\"
    
    For i = 1 To ActivePresentation.Slides.Count
        On Error Resume Next
        ActivePresentation.Slides(i).FollowMasterBackground = msoFalse
        ActivePresentation.Slides(i).Background.Fill.UserPicture picPath & i & ext
        On Error GoTo 0
    Next
    MsgBox "完成匯入 " & ActivePresentation.Slides.Count & " 張圖片"
End Sub

增加錯誤處理(缺圖不中斷)、可調路徑/副檔名、完成提示。

替代方案:相簿功能(無需巨集)

  1. 「插入」→「相簿」→「新增相簿」。
  2. 「檔案/磁碟」→ 選取所有圖片(Ctrl+A)→「建立」。
  3. 自動產生每頁一圖的簡報,可設定版面、標題、相框樣式。

相簿優點:無巨集安全性問題、可批次調整亮度/對比/旋轉、自動生成標題投影片。
巨集優點:完全背景填滿、可整合既有投影片結構、可程式化控制邏輯。

copyright © 萬盛學電腦網 all rights reserved