简体   繁体   中英

EXCEL VBA - LOOP error

I am trying to run a particular function, I tested this yesterday and it works. I wanted this looped but when excel tries the same function for the next row, I get a file path error.

Any ideas? Any help would be much appreciated.

Option Explicit

Sub odoc()

Dim fpath As String
Dim objWord As Object
Dim cel As Range
Dim selectedRange As Range

Set objWord = CreateObject("Word.Application")
fpath = Application.ActiveCell.Value
Set selectedRange = Application.Selection

For Each cel In selectedRange.Cells
objWord.Documents.Open (fpath)
objWord.Visible = True
objWord.Application.Run MacroName:="CopySAM"
ActiveCell.Offset(0, 14).Select
ActiveSheet.Paste
objWord.Application.Quit
ActiveCell.Offset(1, -14).Select
Next cel

End Sub

Thanks.

This tidies up your loop - it should now work. Though I have to say there are better ways to paste the data than the way you're using..

Sub odoc()

    Dim objWord As Object
    Dim cel As Range
    Dim selectedRange As Range

    Set selectedRange = Application.Selection

    For Each cel In selectedRange.Cells
        Set objWord = CreateObject("Word.Application")
        objWord.Documents.Open (cel)
        objWord.Visible = True
        objWord.Application.Run MacroName:="CopySAM"
        cel.Offset(0, 14).Select
        ActiveSheet.Paste
        objWord.Application.Quit
    Next cel

End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM