首页 > 解决方案 > 同时在多张纸上运行宏

问题描述

我有多个工作簿,每个都包含存储在“此工作簿”中的工作簿打开事件代码:

Option Explicit

Private Sub Workbook_Open()
    Call Module4.macro_timer
End Sub

存储在模块 4 中的代码:

Public interval As Double

Sub macro_timer()
    interval = Now + TimeValue("00:03:00")
    Application.OnTime interval, "my_macro"
End Sub

Sub my_macro()
    Workbooks(ThisWorkbook.Name).refreshall
    Call macro_timer
End Sub

所有打开的工作簿都有相同的代码。

当我同时打开这些工作簿时,此代码应该并行运行。当我打开一个工作簿时它可以工作,但是当我打开多个工作簿时它根本不工作。

标签: excelvba

解决方案


我是为我的一位与您情况相同的同事这样做的:

Option Explicit
Sub Main()

    Dim MyPaths As Variant
    Dim MyFiles As Variant
    MyPaths = Array("C:\Users\USER\Desktop\Excel\", _
        "C:\Users\USER\Desktop\Excel\", _
        "C:\Users\USER\Desktop\Excel\", _
        "C:\Users\USER\Desktop\Excel\")
    MyFiles = Array("Tiempos.xlsx", "Tiempos.xlsx", "Tiempos.xlsx", "Tiempos.xlsx")

    Dim i As Long
    Dim MyPath As String
    Dim MyFile As String
    For i = LBound(MyPaths) To UBound(MyPaths)
        MyPath = MyPaths(i)
        MyFile = MyFiles(i)
        NewInstance MyPath, MyFile
    Next i

End Sub
Sub NewInstance(Path As String, File As String)

    Dim exApp As Excel.Application
    Set exApp = New Excel.Application

    exApp.Workbooks.Open Path & File
    exApp.Visible = True

End Sub

您只需要使用自己的路径和文件名编辑MyPaths和数组。MyFiles


推荐阅读