使用动态文件路径位置

时间:2016-04-29 07:21:05

标签: excel vba excel-vba

所以我在Worksheet1中有一个宏打开另一个文件(Worksheet2),然后复制并粘贴特定的单元格并从Worksheet1传输到Worksheet2。

完成Worksheet1的宏复制将单元格从Worksheet1粘贴到Worksheet2后,Worksheet1中的相同宏将触发另一个宏(嵌入在Worksheet2中)来运行。

我从打开Worksheet2开始编写代码,将数据从工作表1复制并粘贴到工作表2,唯一的问题是Worksheet1中的宏触发运行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

我已经知道使用此代码可以实现:

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

注意: SaveAstab 是Worksheet2中宏的名称

但如果您注意到上面的文件位置+文件名+扩展名由用户在特定单元格上输入。我的意思是,文件位置+文件名+扩展名的详细信息是动态的,并由用户输入。

我的问题是,如果我调用我为文件位置+文件名+扩展名指定的单元格,我有错误(运行时错误9)。

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

有人可以分享他们在这件事上的专业知识吗?非常感谢你

1 个答案:

答案 0 :(得分:1)

试试......

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

然后给我输出uf debug.print