View Single Post
 
Old 09-22-2025, 07:44 AM
kilroyscarnival kilroyscarnival is offline Windows 10 Office 2021
Expert
 
Join Date: May 2019
Posts: 362
kilroyscarnival is just really nicekilroyscarnival is just really nicekilroyscarnival is just really nicekilroyscarnival is just really nice
Default

This is the VBA I was trying to get to work. It runs, but I then get as many instances of "Microsoft Excel is waiting for another application to complete an OLE action"

Code:
Sub RunWordMacroFromExcel()
    Dim xlWorksheet As Worksheet
    Dim lastRow As Long
    Dim i As Long
    Dim wordApp As Word.Application
    Dim wordDoc As Word.Document
    Dim filePath As String

    ' Set your worksheet name here
    Set xlWorksheet = ThisWorkbook.Sheets("Sheet1")

    lastRow = xlWorksheet.Cells(xlWorksheet.Rows.Count, "A").End(xlUp).Row

    ' Create a new instance of the Word application
    Set wordApp = New Word.Application
    wordApp.Visible = False ' Set to True for debugging

    ' Loop through each file path in your Excel list
    For i = 1 To lastRow
        filePath = xlWorksheet.Cells(i, "A").Value
        
        ' Check if the file path is not empty
        If filePath <> "" Then
            On Error Resume Next ' In case a file is not found
            
            ' Open the Word document
            Set wordDoc = wordApp.Documents.Open(filePath)

            If Not wordDoc Is Nothing Then
                ' Run the macro stored in Word's Normal.dotm
                wordApp.Run "CompressPhotosWebSaveAndClose"
                
                ' Save and close the document
                wordDoc.Save
                wordDoc.Close
            Else
                ' Handle errors for files that could not be opened
                MsgBox "Could not open file: " & filePath, vbExclamation
            End If
            
            On Error GoTo 0 ' Resume normal error handling
        End If
    Next i

    ' Clean up and close the Word application
    wordApp.Quit
    Set wordDoc = Nothing
    Set wordApp = Nothing
    
    MsgBox "Batch process complete!", vbInformation
End Sub
There's probably a better way to do this, but I haven't worked with VBA between two Office apps before. This is what some searching with AI has suggested. (I know, I know)
Reply With Quote