JohnD59 / work

0 stars 0 forks source link

第二按鈕-=支付起訴WORD 批量加入 圖片 #17

Open JohnD59 opened 1 year ago

JohnD59 commented 1 year ago
Sub PrintDocuments()
    Dim fileToOpen As Variant
    Dim appWord As Object
    Dim doc As Object
    Dim i As Long
    Dim t As Long
    Dim imagePath As String
    Dim shape As Object

    fileToOpen = Application.GetOpenFilename(filefilter:="文檔 (*.doc*), *.doc*", _
    FilterIndex:=4, Title:="請選擇要處理的文檔(可多選)", MultiSelect:=True)

    If Not IsArray(fileToOpen) Then
        MsgBox "你沒有選擇文件", vbOKOnly, "提示"
        Exit Sub
    Else
        ' 初始化Word和Excel應用程式
        Set appWord = CreateObject("Word.Application")

        appWord.Visible = False ' 隱藏Word應用程式視窗

        For i = LBound(fileToOpen) To UBound(fileToOpen)
            ' 打開文件
            Set doc = appWord.Documents.Open(fileToOpen(i))

            ' 插入圖片

            imagePath = "圖片路徑" ' 替換為實際圖片路徑

            Set shape = doc.InlineShapes.AddPicture(Filename:=imagePath, LinkToFile:=False, SaveWithDocument:=True).ConvertToShape
            shape.Left = 333 ' 距離頁面右側

            ' 儲存文件
            doc.Save

            ' 關閉文檔
            doc.Close SaveChanges:=False
            t = t + 1
        Next i

        ' 關閉並釋放資源
        appWord.Quit
        Set appWord = Nothing

    End If

    MsgBox "操作完成!" & vbCrLf & "打印了 " & t & " 個文件。", vbOKOnly, "提示"
End Sub