2013-09-30 56 views
1

我有20个excel工作簿 - 除了它们使用不同的数据以外,每个工作簿都相同。我经常需要改进和更新公式,然后我将它从源工作簿依次复制到其他每个工作簿中。跨多个工作簿重复VBA/Excel宏

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

我是新来的宏,并正在努力与此正确的语法。

我试过以下,但它不起作用。我得到一个“对象变量未设置”的错误信息,我不太明白,也无法解决。

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 

对我失踪的任何帮助将不胜感激。

回答

0

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

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 
+0

谢谢Gary的学生。不幸的是,这仍然给我一个“91”错误 - 对象变量没有设置在目标(1)=“Workbook1.xlsx”行。有什么建议么? – John

0

在尝试了几个不同的事情后,我找到了一个解决方案来避免上述代码的问题。它涉及在数组中设置各种目标工作表的名称。下面

代码工作

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 
相关问题