简体   繁体   中英

Running excel macro from another workbook with dynamic File path location

So I have a macro in Worksheet1 that opens another file (Worksheet2) and then copy and pastes specific cell and transfer from Worksheet1 to Worksheet2.

Once Worksheet1's macro is done copy pasting the cells from Worksheet1 to Worksheet2, the same macro from Worksheet1 will trigger another macro (which embedded in Worksheet2) to run.

I have the codes working from opening Worksheet2, copy and pasting data from worksheet1 to worksheet2, the only problem is the macro in Worksheet1 to trigger to run the macro embedded in Worksheet2.

Sub FCY()
'
' Macro3 Macro
'

    Dim MainFile As Workbook
    Dim jnl As Workbook
    Dim RF As Workbook
    Dim FileExt As String

    Set MainFile = ActiveWorkbook

    'FileExt - Cells where is Worksheet2 being saved (example: Worksheet2.xls)
    FileExt = Sheets("REF Data").Cells(25, 7).Value & "." & Cells(25, 9).Value

    'Set jnl - a command to open the Worksheet2 by using the "FileExt" plus the File Location
    'which is entered in Cells (22,7) or Range("G22") (example - C:\Documents\Worksheet2.xls)
    Set jnl = Workbooks.Open(Worksheets("REF Data").Cells(22, 7).Value & "\" & FileExt)

    'Selecting the specified cells to copy and paste from Worksheet1 to Worksheet2
    MainFile.Activate
    Sheets("FCY").Select
    Range("B11:BJ11").Select
    Range(Selection, Selection.End(xlDown)).Select
    Selection.Copy
    jnl.Activate
    Range("B11:BJ11").Select
    ActiveCell.PasteSpecial xlPasteValues


    'Command which runs another Macro embedded in Worksheet2
    'Incorrect code to run the macro in Worksheet2
    Application.Run (Worksheets("REF Data").Cells(22, 7).Value & "\" & FileExt & SaveAstab)

'
End Sub

I already know that this can be achieve using this code:

Application.Run ("'C:\Documents\Worksheet2.xls'!SaveAstab") 

Note: SaveAstab is the name of the macro in Worksheet2

But if you noticed above the File location + filename + extension name is entered on specific cells by the users. I mean, the details of File location + filename + extension name is dynamic and entered by the users.

My problem is if I call the cells that I assigned for the file location + filename + extension name, I'm having an error (Run Time error 9).

‘Incorrect code to run the macro in Worksheet2
Application.Run (Worksheets("REF Data").Cells(22, 7).Value & "\" & FileExt & SaveAstab)

Could anyone share their expertise on this matter? Thank you very much

Try that...

Dim runCommand as String
runCommand = Chr(39) & Worksheets("REF Data").Cells(22, 7).Value & "\" & FileExt & Chr(39) & "!SaveAstab" 
Debug.print runCommand 
Application.Run(runCommand)

And give me te Output uf debug.print

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