尝试打开工作簿并在该文件中运行宏

时间:2013-03-04 11:20:28

标签: vba excel-vba excel

我有一个工作簿可以打开另一个工作簿(文件名基于单元格值),然后在该文件中运行一个名为Single_sector的宏。

它打开文件完全正常,但不运行宏。有什么想法吗?

Sub run_all()
Dim Location



On Error Resume Next

'Location of file to open
 Location = Worksheets("Main").Range("folder_location").Value

'Open F&V File
Application.Workbooks.Open Location & Range("fv_file").Value
'Run Macro
Run ("Single_sector")



End Sub

3 个答案:

答案 0 :(得分:14)

将以下代码放在调用其他工作簿的宏中:

Location = Worksheets("Main").Range("folder_location").Value
Set wb = Workbooks.Open(Location & Range("fv_file").Value)
Application.Run "'" & wb.Name & "'!" & strSubToRun, Parameters
Set wb = Nothing

参数是您要传递的参数数组,因此其他工作簿中的sub应该类似于

Public Sub TheSub(ParamArray X())

Dim i As Long

Sheet1.Cells(1, 1).Value = "Parameters passed:"

For i = 0 To UBound(X(0))
    Sheet1.Cells(i + 2, 1).Value = CStr(X(i))
Next

End Sub

答案 1 :(得分:3)

enter image description here

请确保您在另一个工作簿中的代码处于Workbook_open事件,因此您不需要使用Run(“Single_sector”)。一旦另一个工作簿打开,过程single_selector就会触发。

更新回答

Sub run_all()
    Dim Location



    On Error Resume Next

    Dim wkb As Workbook

    'Location of file to open
    Location = Worksheets("Main").Range("folder_location").Value

    'Open F&V File
    Set wkb = Workbooks.Open(Location & Range("fv_file").Value)
    wkb.Sheets(1).Single_sector ' kindly put this proc in another workbook sheet1




End Sub

答案 2 :(得分:3)

可能不是很优雅但是:

Dim Location As String

Location = "\\location\to\file.xlsm"

Workbooks.Open(Location).RunAutoMacros (xlAutoOpen) 

您在其他Excel文件中有Auto_Open Sub以处理要在其他电子表格上运行的宏