在多个工作簿中重复执行VBA / Excelmacros

我有20个excel工作簿 – 每个相同,除了他们使用不同的数据。 我经常需要改进和更新公式,然后将其从源工作簿依次复制到其他每个工作簿中。

我使用VBA来logging一个macros(我知道这不是那么优雅)来复制和粘贴所需的更改。 这很好,但是要复制macros20次,每次更改目标工作簿名称都很繁琐。 我的首选解决scheme是通过设置一个循环并依次为每个目标调用macros来自动执行它。

我是新来的macros,并正在努力与这个正确的语法。

我已经尝试了以下,但它不起作用。 我得到一个“对象variables没有设置”的错误消息,我不明白,不能解决。

Sub New() ' Dim i As Integer Dim target As Workbook target(1) = "Workbook1.xlsx" target(2) = "Workbook2.xlsx" 'etc for the other countries For i = 1 To 20 Update Next i End Sub Sub Update() ' Update macro copies updated cells from workbook Country A.xlsx to target workbook Windows("Country A.xlsx").Activate Sheets("Tax").Select Rows("17:26").Select Selection.Copy Windows(target(i)).Activate Sheets("Tax").Select Range("A17").Select ActiveSheet.Paste ' Etc for other changes required End Sub 

任何帮助我失踪将非常感激。

子更新不是“看到”variables 。 考虑:

 Sub New() Dim i As Integer Dim target As Workbook target(1) = "Workbook1.xlsx" target(2) = "Workbook2.xlsx" 'etc for the other countries For i = 1 To 20 Update (i) Next i End Sub Sub Update(i As Integer) ' Update macro copies updated cells from workbook Country A.xlsx to target workbook Windows("Country A.xlsx").Activate Sheets("Tax").Select Rows("17:26").Select Selection.Copy Windows(target(i)).Activate Sheets("Tax").Select Range("A17").Select ActiveSheet.Paste ' Etc for other changes required End Sub 

尝试了几个不同的东西后,我find了一个解决scheme,以避免上述代码的问题。 它涉及设置数组中各种目标工作表的名称。

下面的代码工作

 Sub Newtest() ' Dim target As String Dim targetwb(1 To 2) As String targetwb(1) = "Workbook3.xlsx" targetwb(2) = "Workbook4.xlsx" ' For i = 1 To 2 target = targetwb(i) Test1 (target) Next i End Sub Sub Test1(target) ' ' Copies updated cells from workbook Country A.xlsx to target workbook ' Windows("Country A.xlsx").Activate Sheets("Tax").Select Rows("17:26").Select Selection.Copy Windows(target).Activate Sheets("Tax").Select Range("A17").Select ActiveSheet.Paste ' End Sub