在vba中使用数组而不是不同的subs

我为许多系统开发了一个vba。 我在这里给出两个系统的例子:

Private Sub Macro1() Set x = Workbooks.Open("C:\Users\****\Desktop\New folder\System1.xls") With x.Sheets("System1") Set aCell1 = .Range("A1:X1000").Find(What:="User", LookIn:=xlValues, LookAt:=xlWhole, _MatchCase:=False, SearchFormat:=False) .Range(aCell1, .Cells(.Rows.Count,aCell1.Column).End(xlUp)).Offset(2,0).Copy_ ThisWorkbook.Sheets("System1").Range("A2") End With Private Sub Macro2() Set x = Workbooks.Open("C:\Users\****\Desktop\New folder\System2.xls") With x.Sheets("System2") Set aCell1 = .Range("A1:X1000").Find(What:="User", LookIn:=xlValues, LookAt:=xlWhole, _MatchCase:=False, SearchFormat:=False) .Range(aCell1, .Cells(.Rows.Count,aCell1.Column).End(xlUp)).Offset(2,0).Copy_ ThisWorkbook.Sheets("System1").Range("A2") End With 

有没有办法通过我可以提及一个数组或列表中的所有系统名称,而不是写不同的系统的不同的潜艇? 由于唯一变化的是系统编号

你只需要重构你的代码:

 Private Sub Macro1() GetData 1 End Sub Private Sub Macro2() GetData 2 End Sub Sub GetData(systemNum as long) Set x = Workbooks.Open("C:\Users\****\Desktop\New folder\System" & systemNum & ".xls") With x.Sheets("System" & systemNum) Set aCell1 = .Range("A1:X1000").Find(What:="User", LookIn:=xlValues, LookAt:=xlWhole, _MatchCase:=False, SearchFormat:=False) .Range(aCell1, .Cells(.Rows.Count,aCell1.Column).End(xlUp)).Offset(2,0).Copy_ ThisWorkbook.Sheets("System1").Range("A2") End With End Sub 

尝试添加系统作为参数。 在下面的例子中是一个可选的:

 Option Explicit Private Sub Macro1(Optional strParam As String = "System1") Set x = Workbooks.Open("C:\Users\****\Desktop\New folder\" & strParam & ".xls") With x.Sheets(strParam) Set aCell1 = .Range("A1:X1000").Find(What:="User", LookIn:=xlValues, LookAt:=xlWhole, _MatchCase:=False, SearchFormat:=False) .Range(aCell1, .Cells(.Rows.Count,aCell1.Column).End(xlUp)).Offset(2,0).Copy_ ThisWorkbook.Sheets(strParam).Range ("A2") End With End Sub 

这就是你所说的:

 Public Sub TestMe() Macro1 'same as Macro1 "System1" Macro1 "System1" Macro1 "System2" End Sub 

编辑:至于你想在原来的数组,这是一个可能的解决scheme,你可以修复使用上面的Macro1子:

 Public Sub TestMe() Dim myArr As Variant Dim lngCounter As Long myArr = Array("System1", "System2", "System3") For lngCounter = LBound(myArr) To UBound(myArr) Macro1 myArr(lngCounter) Next lngCounter End Sub